<%@ page import="com.lombardrisk.webgui.util.WebGuiRequestUtils"%>
<%@ page language="java" import="java.util.*" isELIgnored="false" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<%@ taglib uri="/WEB-INF/struts-tiles.tld" prefix="tiles" %>
<%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
<%@ taglib uri="/WEB-INF/struts-logic.tld" prefix="logic" %>
<%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
<%@ taglib uri="/WEB-INF/lrm-html.tld" prefix="lrmhtml" %>

<%@ taglib prefix="c" uri="http://java.sun.com/jstl/core_rt" %>
<%@ taglib uri="http://lrsux.lombardrisk.com" prefix="lrsux" %>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Exposure Management</title>

	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    

	<lrsux:Resource name="lrsux" />
	<lrsux:Resource name="lrsux-ui" />

	<link type="text/css" rel="stylesheet" href="common/styles/layout.css" />
	<link type="text/css" rel="stylesheet" href="common/styles/complex.css" />
	<link type="text/css" rel="stylesheet" href="common/styles/smoothness/jquery-ui-1.8.7.custom.css" />
	<link type="text/css" rel="stylesheet" href="common/script/jquery/jqGrid3.8/css/ui.jqgrid.css" />
    <link type="text/css" rel="stylesheet" href="common/script/jquery/jqGrid3.8/css/ui.multiselect.css" />
    <link type="text/css" rel="stylesheet" href="common/styles/application.css" />
	<link type="text/css" rel="stylesheet" href="common/styles/actionmenu.css" />
    
    <style type="text/css">

		* {
			font-family: Verdana, Arial, Helvetica, sans-serif;
			font-size: 10px;
		}

		a {
			cursor: pointer;
		}

		#loading {
	        position: absolute;
	        width: 100%;
	        height: 100%;
	        text-align: center;
	        padding: 300px 0 0 0;
	        font: bold 12px Verdana,Arial,Helvetica,sans-serif;
			background-color: #ffffff;
			color: #336699;
			z-index: 9999;
	    }
		
		/**
		 * overwrite jQueryUI CSS Starts
		 */
		.ui-state-active, .ui-widget-content .ui-state-active, .ui-widget-header .ui-state-active { BORDER: #afafaf 1px solid; BACKGROUND: url(common/newEEImage/nav_bg.gif) repeat-x; COLOR: #2c2b2b; FONT-WEIGHT: bold; height:25px; }
		.ui-state-default, .ui-widget-content .ui-state-default, .ui-widget-header .ui-state-default { font-family: Verdana,Arial,Helvetica,sans-serif; font-size: 10px; color: #336699 }
		.ui-widget input, .ui-widget select, .ui-widget textarea, .ui-widget button, .ui-widget-content, .ui-autocomplete-input { color: #336699 }
		.ui-accordion-icons .ui-accordion-header a { padding-left: 0.5em; }

		.ui-widget-overlay { background: #aaaaaa url(common/newEEImage/overlay.png) 50% 50% repeat; }
		.ui-widget-shadow { margin: -8px 0 0 -8px; padding: 8px; background: #aaaaaa url(common/newEEImage/overlay.png) 50% 50% repeat-x;  }
		
		#gridPager {height: 18px}
		
		/* main item style*/
		.main-item { margin: 0 0 3px 0; }
		.item-header { BACKGROUND: url(common/newEEImage/panel_bg.gif) #f8f8f8 repeat-x; height:16px; color: #336699; cursor: move; padding: 0 6px; line-height:16px; }
		.item-header .ui-icon { float: right;  cursor:pointer;}
		.item-content { color: #336699; }
		.header { BACKGROUND: url(common/newEEImage/panel_bg.gif) #f8f8f8 repeat-x; color: #336699; border-bottom: 1px solid #777; padding: 0px; text-align: center; line-height:16px; position: relative; overflow: hidden; }
		.footer { background: #718ba6; position: relative; overflow: hidden; color:#fff; border-top: 1px solid #777; text-align: center; font-weight: normal;}

		/* accordion item hover style */
		.item-hover, .item-click {
			COLOR: #2c2b2b;
			BACKGROUND:  #e5f1fa;
			border:1px solid #afafaf
		}

		/* accordion category action style */
		#saveOrderBtn { cursor: pointer; margin-right: 18px; right: 10px; top:0px; position: absolute; width:16px; height:16px; }
		#accordions h3 span {float: right; display: none;}
		
		/* accordion items action style */
		#accordions li span {float: left;}
		#accordions li a {float: right; display: none;}
		
		/* sortable accordion items */
		.connectedSortable li, .sysFilterItems li {color: #336699; margin: 0; font-size: 1em; height: 18px;  padding: 10px 15px;}
		.ui-sortable-placeholder { border: 1px dotted red; visibility: visible !important; height: 20px !important; }
		.ui-sortable-placeholder * { visibility: hidden; }
		.ui-sortable-placeholder-item { border: 1px dotted blue; visibility: visible !important; height: 20px !important; }
		.ui-sortable-placeholder-item * { visibility: hidden; }
		
		/* edit Accordion Item */
		#sysIcons .ui-selecting { background: #FECA40; }
		#sysIcons .ui-selected { background: #F39814; color: white; }
		#sysIcons { list-style-type: none; margin: 0; padding: 0; }
		#sysIcons li { margin: 3px; padding: 1px; float: left; width: 20px; height: 20px; font-size: 1.4em; text-align: center; vertical-align:middle; }
		
		/* Log style */
		.failureLog { color: red }
		.successLog { color: green }
		
		.pagetext {font-family: Verdana, Helvetica, sans-serif; font-size: 10px; color: #336699, padding: 0px}
		tbody tr.odd {background-color: #EEEEEE;} 

		/* Round Corner */
		.ui-corner-tl { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; }
		.ui-corner-tr { -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; }
		.ui-corner-bl { -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; }
		.ui-corner-br { -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; }
		.ui-corner-top { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; }
		.ui-corner-bottom { -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; }
		.ui-corner-right {  -moz-border-radius-topright: 0px; -webkit-border-top-right-radius: 0px; border-top-right-radius: 0px; -moz-border-radius-bottomright: 0px; -webkit-border-bottom-right-radius: 0px; border-bottom-right-radius: 0px; }
		.ui-corner-left { -moz-border-radius-topleft: 0px; -webkit-border-top-left-radius: 0px; border-top-left-radius: 0px; -moz-border-radius-bottomleft: 0px; -webkit-border-bottom-left-radius: 0px; border-bottom-left-radius: 0px; }
		.ui-corner-all { -moz-border-radius: 0px; -webkit-border-radius: 0px; border-radius: 0px; } 
    </style>

	<script type="text/javascript" src="common/script/layout.js"></script>
	<script type="text/javascript" src="common/script/layout-ext.js"></script>
	<script type="text/javascript" src="common/script/cookie.js"></script>
	<script type="text/javascript" src="common/script/browserVer.js"></script>
	<script type="text/javascript" src="common/script/jquery/utils/jquery.blockUI.js"></script>
	<script type="text/javascript" src="common/script/jquery/ui/i18n/jquery-ui-i18n.js"></script>

	<!-- Dev Env -->
<%--	<script type="text/javascript" src="common/script/jquery/jqGrid/ui.multiselect.js"></script>--%>
<%--	<script type="text/javascript" src="common/script/jquery/jqGrid/i18n/grid.locale-en.js"></script>--%>
<%--	<script type="text/javascript" src="common/script/jquery/jqGrid/grid.loader.js"></script>--%>
	
	<script type="text/javascript" src="common/script/jquery/jqGrid3.8/js/i18n/grid.locale-en.js"></script>
    <script type="text/javascript" src="common/script/jquery/jqGrid3.8/plugins/ui.multiselect.js"></script>
    <script type="text/javascript" src="common/script/jquery/jqGrid3.8/jquery.jqGrid.min.js"></script>
    <script type="text/javascript" src="common/script/jquery/jqGrid3.8/plugins/grid.postext.js"></script>


	<script type="text/javascript" src="common/script/jquery/ui-layout/jquery.layout-latest.js"></script>
	<script type="text/javascript" src="common/script/jquery/validate/jquery.validate.js"></script>
	<script type="text/javascript" src="common/script/StringUtil.js" ></script>
	<!-- dwr  -->	
	<script type="text/javascript" src="dwr/interface/GetBookAssetHelper.js"></script>
	<script type="text/javascript" src="dwr/engine.js"></script>
	<script type="text/javascript" src="dwr/util.js"></script>
<%--		<script type="text/javascript" src="common/script/jquery/utils/jquery.jqGridUtil.js"></script>--%>
	
	<script language="JavaScript" type="text/javascript">
		if (!isCollineWinName(window.name,'<%=com.lombardrisk.webgui.util.WebGuiRequestUtils.getWinNameFormat(request)%>')) {
			setCurrentWindowName();
		} 	
	
		jQuery.noConflict();
		jQuery(window).load(
			function(){
				jQuery("#loading").hide();
			}
		);
		
		<c:choose>
			<c:when test="${empty wrapper.id}">
				var cfgId = 0;
			</c:when>
			<c:otherwise>
				var cfgId = <c:out value="${wrapper.id}" />;
			</c:otherwise>
		</c:choose>
		
		var outerLayout, gridPerm;
		var layoutSettings = {
                name: "outerLayout" 
        ,       defaults: {
                        size:                                   "auto"
//                ,       minSize:                                80
                ,       paneClass:                              "pane"          // default = 'ui-layout-pane'
                ,       resizerClass:                   "resizer"       // default = 'ui-layout-resizer'
                ,       togglerClass:                   "toggler"       // default = 'ui-layout-toggler'
                ,       buttonClass:                    "button"        // default = 'ui-layout-button'
                ,       contentSelector:                ".content"      // inner div to auto-size so only it scrolls, not the entire pane!
                ,       contentIgnoreSelector:  "span"          // 'paneSelector' for content to 'ignore' when measuring room for content
                ,       togglerLength_open:             35                      // WIDTH of toggler on north/south edges - HEIGHT on east/west edges
                ,       togglerLength_closed:   35                      // "100%" OR -1 = full height
                ,       hideTogglerOnSlide:             true            // hide the toggler when pane is 'slid open'
                ,       togglerTip_open:                "Close This Pane"
                ,       togglerTip_closed:              "Open This Pane"
                ,       resizerTip:                             "Resize This Pane"
                ,       fxName:                                 "slide"         // none, slide, drop, scale
                ,       fxSpeed_open:                   750
                ,       fxSpeed_close:                  1500
                ,       fxSettings_open:                { easing: "easeInQuint" }
                ,       fxSettings_close:               { easing: "easeOutQuint" }
        }
        ,       north: {
        	 			size:                              91
                ,        spacing_open:                   0                       // cosmetic spacing
                ,       togglerLength_open:             0                       // HIDE the toggler button
                ,       togglerLength_closed:   -1                      // "100%" OR -1 = full width of pane
//                ,		spacing_closed: 0								//either (togglerLength_closed & spacing_closed) eq 0 is hide the toggler button
//                ,       slidable:                               false
                //      override default effect
                ,       fxName:                                 "none"
                }
        ,       south: {
//                        size:                                41
//                ,       spacing_closed:                 10                       // HIDE resizer & toggler when 'closed'
//                ,       slidable:                               true           // REFERENCE - cannot slide if spacing_closed = 0
                       resizable:                               false
                ,       togglerLength_open:             -1                       
                ,       togglerLength_closed:   		-1                      // "100%" OR -1 = full width of pane
                ,       fxName:                                 "none"
                ,		onclose: function() {	jQuery("#jqGrid").jqGrid("setGridHeight", calcGridHeight());}
				,		onopen: function() {	jQuery("#jqGrid").jqGrid("setGridHeight", calcGridHeight());}
                
                }
        ,       west: {
                        size:                                 180
                ,       spacing_closed:                 8                      // wider space when closed
                ,       togglerAlign_closed:    "center"           // align to center of resizer
                ,       togglerLength_closed:   48                      // make toggler 'square' - 21x21
                ,       togglerLength_open:             48                       // toggler button size when status is opened
                ,       togglerTip_open:                "Close West Pane"
                ,       togglerTip_closed:              "Open West Pane"
                ,       resizerTip_open:                "Resize West Pane"
                ,       slideTrigger_open:              "click"         // default
                ,       initClosed:                             false
                //      add 'bounce' option to default 'slide' effect
                ,       fxSettings_open:                { easing: "easeOutBounce" }
				,		onresize:                 function () { jQuery("#accordions").accordion("resize"); }
				,		onclose: function() {	
							jQuery("#jqGrid").jqGrid("setGridWidth", jQuery("#p4").width() - 10);
						}
				,		onopen: function() {
							jQuery("#jqGrid").jqGrid("setGridWidth", jQuery("#p4").width() - 10);
					}
 
                }
        ,       east: {
                        size:                                   90
				,		maxSize:								150
                ,       spacing_closed:                 6                      // wider space when closed
                ,       togglerLength_closed:   48                      // make toggler 'square' - 21x21
                ,       togglerAlign_closed:    "center"          
                ,       togglerLength_open:             48                       
                ,       slideTrigger_open:              "mouseover"
                ,       initClosed:                             false
                //      override default effect, speed, and settings
                ,       fxName:                                 "drop"
                ,       fxSpeed:                                "normal"
                ,       fxSettings:                             { easing: "" } // nullify default easing
                }
        ,       center: {
                        paneSelector:                   "#mainContent"                  // sample: use an ID to select pane instead of a class
                }
        };
		
		
		//init layout
		jQuery(document).ready(function($) {
			
		    // create the OUTER LAYOUT
            outerLayout = $("body").layout(layoutSettings);

            // save selector strings to vars so we don't have to repeat it
            // must prefix paneClass with "body > " to target ONLY the outerLayout panes
            var westSelector = "body > .ui-layout-west"; // outer-west pane
            //var eastSelector = "body > .ui-layout-east"; // outer-east pane

             // CREATE SPANs for pin-buttons - using a generic class as identifiers
            $("<span></span>").addClass("pin-button").prependTo( westSelector );
            //$("<span></span>").addClass("pin-button").prependTo( eastSelector );
            // BIND events to pin-buttons to make them functional
            outerLayout.addPinBtn( westSelector +" .pin-button", "west");
           // outerLayout.addPinBtn( eastSelector +" .pin-button", "east" );

             // CREATE SPANs for close-buttons - using unique IDs as identifiers
            $("<span></span>").attr("id", "west-closer" ).prependTo( westSelector );
            //$("<span></span>").attr("id", "east-closer").prependTo( eastSelector );
            // BIND layout events to close-buttons to make them functional
            outerLayout.addCloseBtn("#west-closer", "west");
            //outerLayout.addCloseBtn("#east-closer", "east");

			$("#eMenuBar").hover(function() {
				outerLayout.allowOverflow(this);
			}, function() {
				outerLayout.resetOverflow(this);
			});
		});
		
		jQuery(function($) {
			
// Main page Navigation 
			
			// ** JS variable
			var itemId;
			var rowData;
			var orignalValue; // remember the orignal counterparty amount value
			var $jqGrid;
			var $treeIds;
			var tempCallStatus;
			var tempComments;
			var isNeedFreshCountNum;
			var $accordions;
			var $selectedCategory;
			var $selectedItem;
			var $multiEditor;
			var $normalEditor;
			var $sysIcons = $("#sysIcons").selectable();
			
			// ** restore the order
			var mainItemsSortable = $("#mainContent");
			var order = $.cookie("sortableOrder");
			
			if (order) {
			      $.each(order.split(","),function(i,id) {
			            //appending the element with the ID, given id should move each element to the end of the 
			            // list one after another, and at the end, the order should be restored.
			            $("#"+id).appendTo(mainItemsSortable);
			      });
			};
			
			// ** init variable properties i.e{ 20100=[12638, 20099, 12639], 10637=[11638, 11637, 11639]} 
			$treeIds = {};
			tempCallStatus = {};
			tempComments = {};
			isNeedFreshCountNum = false;
			
			// ** store the item order in cookie
			mainItemsSortable.sortable({
				handle: '.item-header',
				cursor: 'move',
			    opacity: 0.4, 
			    update: function(e,ui) {
              		order = mainItemsSortable.sortable("toArray").join();
              		$.cookie("sortableOrder",order);
			    }
			      
			});

			// ** hidden the specified panel
			function togglePanel($panel) {
				$panel.find(".item-header a:first").find(".ui-icon").toggleClass("ui-icon-circle-triangle-n").toggleClass("ui-icon-circle-triangle-s");
				$panel.find(".item-content").toggle();
				setTimeout(resetGridHeight, 0);
			}
			
			// ** add show & hide panel
			mainItemsSortable.find(".main-item").addClass("ui-widget ui-widget-content ui-helper-clearfix")
				.find(".item-header")
					.addClass("ui-widget-header")
					.prepend('<a href="javascript:void(0)"><span class="ui-icon ui-icon-circle-triangle-n"></span></a><a href="javascript:void(0)"><span title="maximize" class="ui-icon ui-icon-extlink"></span></a>')
					.find("a:even .ui-icon")
							.click(function() {
								var $msgItem = $("#p3").find(".item-header a:last").find(".ui-icon");
								if($msgItem.attr("title") == 'restore') {
									$msgItem.triggerHandler("click");
									return;
								}
								togglePanel($(this).parents(".main-item:first"));
							})
					.end().end()
					.find("a:odd .ui-icon").toggle(function() {
							var $actionItem = $("#p5");
							var $girdItem = $("#p4");
							var $curItem = $(this).parents(".main-item:first");

							if(!$actionItem.find(".item-content").is(":hidden")) {
								togglePanel($actionItem);
							}
							if(!$girdItem.find(".item-content").is(":hidden")) {
								togglePanel($girdItem);
							}
							if($curItem.find(".item-content").is(":hidden")) {
								togglePanel($curItem);
							}
							
							$(this).toggleClass("ui-icon-newwin").toggleClass("ui-icon-extlink").attr('title', 'restore');
							$("#p3 .item-content").height(calcMsgPanelHeight());
							
						}, function() {
							var $actionItem = $("#p5");
							var $girdItem = $("#p4");
							var $curItem = $(this).parents(".main-item:first");

							if($actionItem.find(".item-content").is(":hidden")) {
								togglePanel($actionItem);
							}
							if($girdItem.find(".item-content").is(":hidden")) {
								togglePanel($girdItem);
							}
							if($curItem.find(".item-content").is(":hidden")) {
								togglePanel($curItem);
							}

							$(this).toggleClass("ui-icon-newwin").toggleClass("ui-icon-extlink").attr('title', 'maximize');
							$("#p3 .item-content").height(48);
						});

			// hidden the Action & Grid Panel maximum button
			$("#p4, #p5").find(".item-header").find("a:odd").hide();

			// ** main center panel end ------------------------
			
			$(window).resize(function() {
				setTimeout(resetGridHeight,500);
				setTimeout(resetGridWidth,500);
			});
			
			function addCommas(nStr) {
				nStr += '';
				x = nStr.split('.');
				x1 = x[0];
				x2 = x.length > 1 ? '.' + x[1] : '';
				var rgx = /(\d+)(\d{3})/;
				while (rgx.test(x1)) {
					x1 = x1.replace(rgx, '$1' + ',' + '$2');
				}
				return x1 + x2;
			}
			
			function convertAmount2Opposite(inputValue) {
				return parseFloat(inputValue) < 0 ? inputValue.substring(1, inputValue.length) : "-" + inputValue;
			}
			
			function convertString2Float(val) {
				return parseFloat(val.replace(/,/g,""));
			}
	
			// ** custom fomatters & editors start -----------------
			function emptyValueFmtter (cellvalue) {
				if(!cellvalue) cellvalue = "&nbsp;"
				return cellvalue;
			}

			function standardFmtter(cellvalue, options, rowObject) {
				if(rowObject['_' + options.colModel.name]) {
					cellvalue = rowObject['_' + options.colModel.name];
				}
				
				return emptyValueFmtter(cellvalue);
			}
			
			function ccyFmtter(cellvalue, options, rowObject) {
				return addCommas(cellvalue);
			}
			
			function treeIconFmtter (cellvalue, options, rowObject){
				
				var treeIcon;
				if(rowObject.umbrellaType == 0) {
					//treeIcon =  "<span class='ui-icon ui-icon-radio-off' width='13' height='13' />";
					treeIcon =  emptyValueFmtter("");
				} else {
					if(rowObject.umbrellaType == 1) {
						treeIcon =  "<span class='tree-button-add' language='"+rowObject.workflowStatus+"' lang='"+rowObject.agreementStatus+"' title='" + options.rowId + "'/>";
					} else if(rowObject.umbrellaType == 2 && rowObject.parentId != 0){
						treeIcon =  "<span class='tree-button-line' style='margin-left: 20px;'/>";
					} else {
						treeIcon =  emptyValueFmtter("");
					}
				}
				
				return treeIcon;
			}

			function redStarFmtter (cellvalue, options, rowObject){
				if(rowObject.deadline)	cellvalue =  "<font style='color:red'>*</font>" + cellvalue;
				
				return emptyValueFmtter(cellvalue); 
			}

			function stmtStatusFmtter (cellvalue, options, rowObject){
				if(rowObject.statementStatus == ${approved}) {
					cellvalue = "<img src='common/newEEImage/tickg.gif' width='13' height='13'/>";
				}else {
					if(rowObject.statementStatus == ${inProcess}) cellvalue = "<div>IP</div>";
					else cellvalue = "<img src='common/newEEImage/crossg.gif' width='13' height='13'/>";
				}
				
				return emptyValueFmtter(cellvalue); 
			}
			
			function eventSourceFmtter (cellvalue, options, rowObject){
				
				if(rowObject.nonNet) cellvalue = "${notNetLabel}";
				else {
					if(rowObject.eventSource == ${net}) cellvalue = "${netLabel}";
					else if(rowObject.eventSource == ${lockUp}) cellvalue = "${autoNetLabel}";
				}
				
				return emptyValueFmtter(cellvalue); 
			}

			function notificationFmtter(cellvalue, options, rowObject){
				if(!isNaN(cellvalue))	
					cellvalue = options.colModel.searchoptions.value[cellvalue];
				
				return emptyValueFmtter(cellvalue); 
			}

			function tickImgFmtter (cellvalue, options, rowObject){
				
				if(cellvalue) cellvalue = "<img src='common/newEEImage/tickg.gif' width='13' height='13'/>";
				
				return emptyValueFmtter(cellvalue); 
			}
			
			function disputedAgeFmtter (cellvalue, options, rowObject){
				
				if(rowObject.disputedValue < 0) cellvalue = rowObject.disputeAge;
				
				return emptyValueFmtter(cellvalue); 
			}
			
			function agrBaseCcyFmtter (cellvalue, options, rowObject){
				
				cellvalue =  "<font style='color:#CC0000'>" + cellvalue + "</font>";
				
				return emptyValueFmtter(cellvalue); 
			}
			
			function workFlowStatusFmtter (cellvalue, options, rowObject){
				
				if(cellvalue == 68) cellvalue = "Approved";
				else if(cellvalue == 69) cellvalue = "Amended";
				else if(cellvalue == 70) cellvalue = "Amended-Waived";
				
				return emptyValueFmtter(cellvalue); 
			}

			function workflowElem(value, options) {
				var curUserData = getUserData(rowData.workflowId);
				var fourEyeData = curUserData.fourEyeData;
				var workflowStatusData = curUserData.workflowStatusCollection;
				
				var selectElem = document.createElement("select");
				
				for(var p in workflowStatusData) {
					if(p) {
						var option = new Option(workflowStatusData[p], p);
						selectElem.options.add(option);
						if(value == workflowStatusData[p]) {
							option.selected = true;
						}
					}
				}
				if(value != "Approved" && !fourEyeData.workflowStatus4eyesCheck)
					selectElem.disabled = true;
				
				editFocusTrigger($(selectElem));
				return selectElem;
			}

			function workflowValue(elem) {
				return elem.val();
			}
			

			function callStatusFmtter (cellvalue, options, rowObject){

//				if(typeof(cellvalue) == "number")	
				if(!isNaN(cellvalue))	
					cellvalue = options.colModel.searchoptions.value[cellvalue];

//				if(cellvalue == 0) cellvalue = " ";
//				else if(cellvalue == 65) cellvalue = "Pending Review";
//				else if(cellvalue == 58) cellvalue = "No Call Required";
//				else if(cellvalue == 204) cellvalue =  "Waived";
//				else if(cellvalue == 205) cellvalue = "Completed";
//				else if(cellvalue == 150) cellvalue =  "------";
//				else if(cellvalue == 55) cellvalue = "Margin Request Issued";
//				else if(cellvalue == 56) cellvalue = "Margin Request Confirmed";
//				else if(cellvalue == 145) cellvalue = "Partial Dispute";
//				else if(cellvalue == 146) cellvalue = "Full Dispute";
//				else if(cellvalue == 59) cellvalue = "Margin Request Received";
//				else if(cellvalue == 149) cellvalue = "Collateral Booked";
				
				return emptyValueFmtter(cellvalue); 
			}

			function callStatusElem(value, options) {
				var curUserData = getUserData(rowData.workflowId);
				var fourEyeData = curUserData.fourEyeData;
				var callStatusData = curUserData.callStatusCollection;
				
				var selectElem = document.createElement("select");
				
				for(var p in callStatusData) {
					if(p) {
//						console.log(p);
						var option = new Option(callStatusData[p], p);
						selectElem.options.add(option);
						if(value == callStatusData[p]) {
							option.selected = true;
						}
					}
				}
				if(!fourEyeData.callStatus4eyesCheck) selectElem.disabled = true;
				
				if(!tempCallStatus[rowData.workflowId]) tempCallStatus[rowData.workflowId] = value;
				//value == 'Completed'
				//filterId == "CompletedFilter"
				if(tempCallStatus[rowData.workflowId] == 'Completed') {
					$(selectElem).change(function(event) {
						if(checkCallStatusChanged($(this).val())) {
							$(this).val(205);
							return ;
						}
					});
				} else if(rowData.eeInitTab == 3 || rowData.eeInitTab == 7) {
					$(selectElem).change(function(event) {
						//update the other associate event when in call & call tab or delivery & return tab 
						callStatusChanged($(this));
					});
				}
				
				editFocusTrigger($(selectElem));
				return selectElem;
			}
			
			function callStatusValue(elem) {
				return elem.val();
			}
			
			function udcStatusElem(value, options) {
				var selectElem = document.createElement("select");
				
				for(var p in options.value) {
					if(p) {
						var option = new Option(options.value[p], p);
						selectElem.options.add(option);
						if(value == options.value[p]) {
							option.selected = true;
						}
					}
				}
				editFocusTrigger($(selectElem));
				return selectElem;
			}
			
			function udcStatusValue(elem) {
				return elem.val();
			}
			
			function udfStatusFmtter (cellvalue, options, rowObject){
				if(!isNaN(cellvalue))	
					cellvalue = options.colModel.searchoptions.value[cellvalue];
				
				return emptyValueFmtter(cellvalue); 
			}
			
			function agreedAmountElem(value, options) {
				var curRowData = getRowData(rowData.workflowId);
				var curUserData = getUserData(rowData.workflowId);
				var fourEyeData = curUserData.fourEyeData;
				
				var inputElem = document.createElement("input");
				inputElem.type="text";
				inputElem.value = value;
				
				if(getRowData(rowData.workflowId).overwrite == "false" || getRowData(rowData.workflowId).overwrite == "") inputElem.disabled = true;
				if(!fourEyeData.agreedAmount4eyesCheck) inputElem.disabled = true;
				
				editFocusTrigger($(inputElem));
				return inputElem;
			}
			
			function agreedAmountValue(elem) {
				return elem.val();
			}
			
			function overwriteElem(value, options) {
				var curUserData = getUserData(rowData.workflowId);
				var fourEyeData = curUserData.fourEyeData;
				
				var checkBoxElem = document.createElement("input");
				
 				checkBoxElem.type = "checkbox";

				if(value == "true")	{
					checkBoxElem.checked = true;
					
					//fix IE7 could not checked bug
					checkBoxElem.defaultChecked = true;
				}
				if(!fourEyeData.overwrite4eyesCheck) checkBoxElem.disabled = true;
				
				editFocusTrigger($(checkBoxElem));
				return checkBoxElem;
			}
			
			function overwriteValue(elem) {
//				return elem.val();
				return elem.attr("checked");
			}
			
			function ctpyAmtElem(value, options) {
				orignalValue = value;
				
				var $elem = $("<span/>").append("<input value='" + value + "'/>").prepend("<img src='common/newEEImage/exchange.gif' width='13' height='13'/>");
				$multiEditor = $elem.find("input");
				$elem.find("img")
					.hover(function() {
							$(this).css("cursor", "pointer");
						}, function() {
							$(this).css("cursor", "move");
						})
					.click(function() {
						$("#errorMsg").text("");
						$("select[name='originalCurrency']").val(getUserData(rowData.workflowId).agrBaseCcy);
						$("select[name='resultCurrency']").val(getUserData(rowData.workflowId).agrBaseCcy);				
						$("#_originalAmount").val($(this).siblings().val());	
	
						$("#dialog-ccyExchange").dialog('open');
						
					});
				
				editFocusTrigger($elem.find("input"));
				return $elem[0];
			}
			
			function ctpyAmtValue(elem) {
				var flag;
				var inputValue = elem.find("input").val();
				
				//if the counterparty value is not changed, return the value directly
				if(orignalValue == inputValue) {
					return inputValue;
				}

				if(isNaN(parseInt(inputValue))) {
					inputValue = "0.00";
				}
				var fundEventId = parseInt(elem.prevObject.parent().attr("id"));
				var workflowData = getRowData(fundEventId);
				
				if(workflowData.movementRequiredId == 51 || workflowData.movementRequiredId == 52) {
					if(parseFloat(inputValue) < 0) {
						//$dialogConfirmMsg.dialog('open');
						flag = window.confirm("Entering this value implies a Full Dispute, Would you like to reverse the sign?");
					}
					
				}else if(workflowData.movementRequiredId == 53 || workflowData.movementRequiredId == 54) {
					if(parseFloat(inputValue) > 0) {

						flag = window.confirm("Entering this value implies a Full Dispute, Would you like to reverse the sign?");
					}
				}
				
				if(flag) inputValue = convertAmount2Opposite(inputValue);
				
				var umbrellaId = getUmbrellaId(fundEventId); 
				
				if(umbrellaId) {
					var umRowData = getRowData(umbrellaId);
					
					var fundAmts = new Array();
					var fundAmt;
					var fundRowData;
					$.each($treeIds[umbrellaId], function(index, elem) {
						fundRowData = getRowData(elem);
						fundAmt = new Object();
						
						if(fundEventId === elem) {
							fundAmt.amtValue = inputValue;
							fundAmt.changed = true;
						} else {
							fundAmt.amtValue = fundRowData["marginDelvCtpy"];
							fundAmt.changed = false;
						}
												
						fundAmt.currency = getUserData(elem).agrBaseCcy;
						fundAmt.actionId = fundRowData["movementRequiredId"];
						
						fundAmts.push(fundAmt);
					});

					sendSyncRequest({	
						method: 'ctpyAmtChange',
						umbrellaCcy: getUserData(umbrellaId).agrBaseCcy,
						marketDataId: umRowData.marketDataId,
						umbCcyChange: false,
						fundAmts:  JSON.stringify(fundAmts)
					}, function(data){
						
						$('#' + umbrellaId).addClass("edited");
						
						setCellManually(umbrellaId, 'marginDelvCtpy', data.totalValue);
						setCellManually(umbrellaId, 'marginDelvCtpyUmbBaseCcy', data.totalValue);
						setCellManually(fundEventId, 'marginDelvCtpyUmbBaseCcy', data.fundValue);
					}, "", "", true);

	            }		
				return inputValue;
			}
			
			function ctpyExposureValue(elem) {
				return elem.find("input").val();
			}
			
			function umCtpyAmtElem(value, options) {
				var inputElem = document.createElement("input");
				inputElem.type="text";
				inputElem.value = value;

				editFocusTrigger($(inputElem));
				return inputElem;
			}
			
			function umCtpyAmtValue(elem) {
				var inputValue = elem.val();
				var fundEventId = parseInt(elem.prevObject.parent().attr("id"));
				var umbrellaId = getUmbrellaId(fundEventId); 
				
				if(umbrellaId) {
					var umRowData = getRowData(umbrellaId);
					
					var fundAmts = new Array();
					var fundAmt;
					var fundRowData;
					$.each($treeIds[umbrellaId], function(index, elem) {
						fundRowData = getRowData(elem);
						fundAmt = new Object();
						
						if(fundEventId === elem) {
							fundAmt.amtValue = inputValue;
							fundAmt.changed = true;
						} else {
							fundAmt.amtValue = fundRowData["marginDelvCtpyUmbBaseCcy"];
							fundAmt.changed = false;
						}
												
						fundAmt.currency = getUserData(elem).agrBaseCcy;
						fundAmt.actionId = fundRowData["movementRequiredId"];
						
						fundAmts.push(fundAmt);
					});

					sendSyncRequest({	
						method: 'ctpyAmtChange',
						umbrellaCcy: getUserData(umbrellaId).agrBaseCcy,
						marketDataId: umRowData.marketDataId,
						umbCcyChange: true,
						fundAmts:  JSON.stringify(fundAmts)
					}, function(data){

						$('#' + umbrellaId).addClass("edited");
						
						setCellManually(umbrellaId, 'marginDelvCtpy', data.totalValue);
						setCellManually(umbrellaId, 'marginDelvCtpyUmbBaseCcy', data.totalValue);
						setCellManually(fundEventId, 'marginDelvCtpy', data.fundValue);
						
	                }, "", "", true);		
				}
				return inputValue;
			}
			
			function commentsElem(value, options) {
				
				var $elem = $("<span/>").append("<textarea cols='25' rows='1' style='overflow-y:auto;'>" + value + "</textarea>").prepend("<img src='common/newEEImage/edit.gif' width='13' height='13'/>");
				$multiEditor = $elem.find("textarea");
				if(!tempComments[rowData.workflowId]) tempComments[rowData.workflowId] = value;
				$elem.find("img")
					.hover(function() {
							$(this).css("cursor", "pointer");
						}, function() {
							$(this).css("cursor", "move");
						})
					.click(function() {
						
						$("#txtComments").val($(this).siblings().val());	
	
						$("#dialog-comments").dialog('open');
						
					});
				editFocusTrigger($elem.find("textarea"));
				return $elem[0];
			}
			
			function commentsValue(elem) {
				return elem.find("textarea").val();
			}
			
			function resetGridHeight() {
				$jqGrid.jqGrid("setGridHeight", calcGridHeight());
			}
			
			function resetGridWidth() {
				$jqGrid.jqGrid("setGridWidth", $("#p4").width() - 10);
			}
			
			function getfilterIdByItem(itemId){
		    	return $('#'+itemId).attr('filter');
		    }
			
			function getRowData(workflowId) {
				return $jqGrid.jqGrid("getRowData", workflowId);
			}

			function getUserData(workflowId) {
				return $jqGrid.getGridParam('userData')[workflowId];
			}
			
			function getUmbrellaId(fundEventId) {
				var umbrellaId;
				$.each($treeIds, function(i, val) {	
					if($.inArray(fundEventId, val) !== -1) {
						umbrellaId = parseInt(i);
						return false; 
					}
				});
				return umbrellaId;
			}
			
			function getChangedUmbrellaIds(changedArr) {
				var eventIds = new Array();
				$.each(changedArr, function(index, value) {
					var associateEventId;
					var eventId = parseFloat(value.id);
					var rowData = getRowData(eventId);
					var userData = getUserData(eventId);

					var umId = getUmbrellaId(eventId);
					if(umId) {
						eventId = umId;
					} 
					
					if($.inArray(eventId, eventIds) === -1) {
						eventIds.push(eventId);
					}
					
					//fix delivery amount need to be return first
					if ((itemId == "deliveryReturn" || itemId == "dynamic") && userData.umbrellatype == 0) {
						var trs = $jqGrid.jqGrid("getRowData");
						if (trs != "" && trs != null) {
							for (var i = 0; i < trs.length; i++) {
								if ((trs[i].workflowId != rowData.workflowId) && (trs[i].historical == rowData.historical) && (trs[i].eventDate == rowData.eventDate) && (trs[i].agreementId == rowData.agreementId) && (trs[i].eeInitTab == rowData.eeInitTab) && (trs[i].eventSource == rowData.eventSource)) {
									associateEventId = parseFloat(trs[i].workflowId);
									break;
								}
							}
						}
						if(associateEventId && $.inArray(associateEventId, eventIds) === -1) {
							eventIds.push(associateEventId);
						}
					}
					
				});
				
				return eventIds;
			}
			
			function setCellManually(rowId, colname, value) {
				updateDirtyData(rowId, colname);
				$jqGrid.jqGrid("setCell", rowId, colname, value, false, false, true);
				
			}
			
			function updateDirtyData(rowId, colname) {
				var iCol = getColNumByName(colname);
				$("td:eq("+iCol+")",$("#" + rowId)).addClass("dirty-cell");
			}
			
			function getColNumByName(colname) {
				var pos;	
				$($jqGrid[0].p.colModel).each(function(i){
					if (this.name == colname) {
						pos = i;return false;
					}
				});
				return pos;
			}
			// ** custom fomatters & editors end -----------------
			
			// ** logic JS Starts ---------------
			function checkCallStatusChanged(value) {
		    	if (value != 58 && value != 205) {
		    		alert("The entry can only be changed to 'No Call Required'!");
		    		return true;
		    	}
		    }
		    
			function callStatusChanged($elem) {
		    	
//		    	var rowData = getRowData($elem.parent().parent().parent().attr("id"));
		    	
		    	var callStatus = $elem.val();
		    	
				var agreementId = rowData.agreementId;
				
				var eventSource = rowData.eventSource;
				
				var eventDate = rowData.eventDate;
				
				var historical = rowData.historical;
				
				var trs = $jqGrid.jqGrid("getRowData");
				if (trs != "" && trs != null) {
					
					for (var i=0; i<trs.length;i++) {
						if ((trs[i].workflowId !=  rowData.workflowId) && (trs[i].historical == historical) && (trs[i].eventDate == eventDate)&&(trs[i].agreementId == agreementId)&&(trs[i].eeInitTab == rowData.eeInitTab)&&(trs[i].eventSource == eventSource)&&(trs[i].callStatus!= callStatus )) {
							$('#' + trs[i].workflowId).addClass("edited");
							setCellManually(trs[i].workflowId, 'marginCallStatus', callStatus);
							break;
						}
					}
				}
		    }

			// ** logic JS Ends ---------------
			
			// ** data grid
			var jqConfig = ${jqCfg};
            var DEFAULT_COLUMN_ORDER=${defaultColumnOrder};
			jqConfig.url = parseUrlWithWinName(jqConfig.url);
			$jqGrid = jQuery("#jqGrid").jqGrid(jqConfig);

			jQuery.extend(true,$.jgrid,{
				formatter : {
				    checkbox : {disabled:false}
				}
			});
			resetGridHeight();
			
			setTooltipsOnColumnHeaders();
			$(".ui-pg-input").keypress(function(event) {
		   		if ( ((event.keyCode > 47) && (event.keyCode < 58)) || (event.keyCode == 8) ) {  
		            return true;  
		        } else {
		            return false;  
		        }  
			});
			// ** set Grid Header tooltip
			function setTooltipsOnColumnHeader(colname, text) {
			    $("#jqGrid_" + colname).attr("title", text);
			}
			
			function setTooltipsOnColumnHeaders() {
				setTooltipsOnColumnHeader("released", "Released By Client");
				setTooltipsOnColumnHeader("sysDraftPresent", "System Draft Booked");
				setTooltipsOnColumnHeader("calcAgent", "Calculation Agent");
				setTooltipsOnColumnHeader("clBreached", "Concentration Limits Breached");
				setTooltipsOnColumnHeader("verified", "Counterparty Entered Value");
				setTooltipsOnColumnHeader("stdAmount", "Split The Difference");
				setTooltipsOnColumnHeader("legalFrequencyPeriod", "Legal Review Frequency ");
				setTooltipsOnColumnHeader("legalFrequencyDays", "Legal Review Frequency Days");
			}
			
			
			var lang = '<%=WebGuiRequestUtils.getLocale(request).getLanguage()%>';
			if('<%=WebGuiRequestUtils.getLocale(request).getCountry()%>') {
				lang = '<%=WebGuiRequestUtils.getLocale(request).getLanguage()%>-<%=WebGuiRequestUtils.getLocale(request).getCountry()%>';
			}
			
			function datePick(elem) {
				jQuery.datepicker.setDefaults(jQuery.datepicker.regional[lang]);
				jQuery(elem).datepicker({ 
					showAnim: 'show',
					onClose: function(dateText, inst){
						$jqGrid[0].triggerToolbar();
					}
				});
			}
			
			// ** Save Data Filter Method
			var saveDataFilter = function() {
				if(!itemId) return;
				var $filter = $("#"+getfilterIdByItem(itemId));
				if($filter.parent().parent().hasClass("sysFilterItems")) {
					alert("could not modify the System Filter");
					return ;
				}
				
				var $inputs = $filter.siblings(":input");
				var $tabPage = $inputs.filter("[name='tabPage']");				
				var filterItems = new Array();
				var filterItem; 
				if($tabPage.attr("name")=="tabPage"){
					filterItem = new Object();
					filterItem.fieldName ="tabPage";
					filterItem.filterValue = $tabPage.val();
					filterItems.push(filterItem);
				}
				$("select,:text", "#p4 .ui-search-toolbar").each(function(i) {
					filterItem = new Object();
					filterItem.fieldName = $(this).attr("id").replace("gs_", "");
				
				//advanced search need matchType
//					filterItem.filterType = "CONTAINS";
					filterItem.filterValue = $(this).val();
					filterItems.push(filterItem);
					
					var $input = $inputs.filter("[name='" + filterItem.fieldName + "']");
					if($input.length == 0) {
						$input = $("<input>", {
							"type": 'hidden',
							"name": filterItem.fieldName
//							"value": filterItem.filterValue
						});
						$input.insertAfter($inputs.length == 0 ? $filter : $inputs);
					}
					$input.val(filterItem.filterValue);
				});
				
				sendSyncRequest({	
						method: 'updateDataFilter',
						cfgId: cfgId,
						filterId: getfilterIdByItem(itemId),
						filter: JSON.stringify(filterItems)
					}, function(data){
	                   cfgId = data.cfgId;
	                   $("#" + getfilterIdByItem(itemId)).siblings("b").html("("+data.filterResCount+")");
	                });	
				
			}
			
			var clearDataFilter = function(){ 
				var sgrid = $jqGrid[0];
				sgrid.clearToolbar();
			}
			
			var triggerToolbarSearch = function() {
				//need to fresh the filter count number
				isNeedFreshCountNum = true;
				
				var sgrid = $jqGrid[0];
				sgrid.triggerToolbar();
				$("#load_jqGrid").removeClass("ui-state-active").css({ width: "100px", height: "20px", "padding-top": "10px"});
			}
			
			function checkGridStatus() {
				if($jqGrid.jqGrid("getGridParam", "datatype") != 'json') {
					$jqGrid.jqGrid("setGridParam", {datatype: "json"});
					return true;					
				}
			}
			
			var addOption = function(filterName,label){
				
				var selObj=document.getElementById("copyfilter");
				selObj.options.add(new Option(label,filterName));
				
			}

			var removeOption = function(filterName){
				var sel=document.getElementById("copyfilter").options;
			        for(var i = 0; i < sel.length; i++) {
			            if (sel[i].value == filterName) sel.remove(i);
			        }
			}
			
			// ** top toolbar 'Save' & 'Clear' Filter Buttons	
<%--			$("#jqGrid").toolbarButtonAdd("#t_jqGrid",{--%>
<%--					caption:"",--%>
<%--					title:"Save Filters", --%>
<%--					position:"first",--%>
<%--					align:"right", --%>
<%--					buttonicon:"ui-icon-disk", --%>
<%--					onClickButton: saveDataFilter --%>
<%--				})--%>
<%--				.toolbarButtonAdd("#t_jqGrid",{--%>
<%--					caption:"",--%>
<%--					title:"Clear Fiters", --%>
<%--					buttonicon:"ui-icon-refresh", --%>
<%--					onClickButton: clearDataFilter --%>
<%--				});--%>
	
			// ** bottom toolbar Buttons
			// [ -- 'Nav Pagination' & 'Save Filter' & 'Clear Filter' & 'Reorder Columns' -- ]
			$jqGrid.jqGrid('navGrid','#gridPager',{add:false,del:false,edit:false,view:false,search:false,refresh:false,position:'left'})
				.jqGrid('navButtonAdd','#gridPager',{
					caption:"Save",
					title:"Save Filters", 
					buttonicon:"ui-icon-disk", 
					onClickButton: saveDataFilter, 
					position:"last"
						
				})
				.jqGrid('navButtonAdd','#gridPager',{
					caption:"Clear",
					title:"Clear Filters", 
					buttonicon:"ui-icon-refresh", 
					onClickButton: clearDataFilter,
					position:"last"
						
				});

	
			$jqGrid.jqGrid('navButtonAdd','#gridPager',{
			    caption: "Columns",
			    title: "Reorder Columns",
                onClickButton: function(){
                    $jqGrid.jqGrid('columnChooser', {
                        done: function(perm){
                            if (perm) {
							
								$jqGrid.remapColumns(perm, true);
								var colModel = $jqGrid.jqGrid("getGridParam", "colModel");
								var currentColum = [];
								var hiddenIds = [];
								
								for (var ik = 1; ik < colModel.length; ik++) {
									currentColum[currentColum.length] = colModel[ik].name;
									if (colModel[ik].hidden) {
										hiddenIds[hiddenIds.length] = colModel[ik].name;
									}
								}
								var columnSaveOrder = [];
								for (var st = 0; st < currentColum.length; st++) {
									for (var si = 0; si < DEFAULT_COLUMN_ORDER.length; si++) {
										if (currentColum[st] == DEFAULT_COLUMN_ORDER[si]) {
											columnSaveOrder[st] = si;
											break;
										}
									}
								}
								var hiddenIdOrder = [];
								for (var u = 0; u < hiddenIds.length; u++) {
									for (var su = 0; su < DEFAULT_COLUMN_ORDER.length; su++) {
										if (hiddenIds[u] == DEFAULT_COLUMN_ORDER[su]) {
											hiddenIdOrder[u] = su;
											break;
										}
									}
								}
								//get the columnSettingId by itemId, in case the itemId is empty, the default will be the columnSettingId
								var columnSettingId = itemId ? $('#' + itemId).attr("columnsetting") : 'default';
								var ajaxData = {
									method: 'updateGridPro',
									cfgId: cfgId,
									columnSettingId: columnSettingId,
									hiddenIds: JSON.stringify(hiddenIdOrder),
									perm: JSON.stringify(columnSaveOrder),
                                    sortName: $jqGrid.jqGrid('getGridParam','sortname'),
                                    sortOrder:$jqGrid.jqGrid('getGridParam','sortorder')
								};
								if (!itemId) {
									ajaxData.cfgPerm = JSON.stringify(perm);
								}
								sendSyncRequest(ajaxData, function(data){
									cfgId = data;
								});
							}
                        }
                    });
                }
			});
			
			$jqGrid.jqGrid('filterToolbar',{
				searchOnEnter : true,
				stringResult: false,
				beforeSearch: function() {
					if(checkGridStatus()) {
						// remove filters post data on ajax request when search data directly without click filter button
						// TODO need to support advanced search in Phrase II
						$jqGrid.jqGrid("removePostDataItem", "filters");
						$jqGrid[0].triggerToolbar();
						return false;
					}
				}
			});
			$jqGrid.jqGrid('setGridParam',{ 
			    beforeRequest: function() {
					blockUI();
				},
				serializeGridData: function(postData){
					return postData;
				},
				formatCell: function(rowid, cellname, value, iRow, iCol){
					rowData = $jqGrid.jqGrid("getRowData",rowid);
				},
				afterEditCell: function(rowid, cellname, value, iRow, iCol){
					disableFields(rowid, cellname, value, iRow, iCol);
				
				},
				afterSaveCell: function(rowid){
					afterSaveCellInvocation(rowid);
				},
				loadComplete: function(data){
					$(".ui-layout-west, #mainContent").unblock();
					if(data.errorHappened){
						log(data.message, false);
					}else{
						isSaveSuccessfull();

						//init data and bind event
						$treeIds = {};
						tempCallStatus = {};
						addChkEvent();
						addTreeEvent();
						tempComments = {};
						//do bussiness logic
						//to custom the behavior of overwrite tick box	
						addOverwriteEvent();				
						changeColor(data);
						showCalclateMessage();
						updateCountsForCurrCategory();
						actionBtnCheckRequest();
                        //below code is to show the sort icons of clicked head.
                        $("div.ui-jqgrid-sortable", $jqGrid[0].grid.hDiv).click(function() {
                            if (iconsIsHidden) {
                                iconsIsHidden = false;
                                $(this).find("span.s-ico").show();
                            }
                        });
					}

				},
				loadError: function(xhr,status,error) {
					if (!sessionTimeOutCheck(error)) {
						$(".ui-layout-west, #mainContent").unblock();
					}
				}
			});

			var afterSaveCellInvocation = function(rowid){
				if(!$("#jqg_jqGrid_" + rowid).attr("checked")){
					$("#jqg_jqGrid_" + rowid).click().attr("checked",true);
					actionBtnCheckRequest();
				}
			}

            var addOverwriteEvent = function(){
				
				$('td[aria-describedby="jqGrid_overwrite"]').each(function(){
                    //four eye check
                    var rowId = $(this).parent().attr('id');
	                var $overwrite = $(this).children('input');
	                var curUserData = getUserData(rowId);
					var overwrite4eyesCheckFlag = curUserData.fourEyeData.overwrite4eyesCheck;
					if(!overwrite4eyesCheckFlag) $overwrite.attr('disabled', 'disabled');

					$(this).click(function(e){
						//save the cell befor click this 
						$jqGrid.jqGrid("saveCell",$jqGrid[0].p.iRow,$jqGrid[0].p.iCol);
	                    if(overwrite4eyesCheckFlag){
		                    var iCol = $.jgrid.getCellIndex(this);
		                    $newOverwrite = $(this).children('input');
		                    $('#' + rowId).addClass("edited");
		                    
		                    setCellManually(rowId, 'overwrite', $newOverwrite.attr('checked'));
		                    
		                    afterSaveCellInvocation(rowId);
		                    
		                     //composite checked, will set both events	
		                    overwriteCheckedChanged($(this).children('input'), rowId);
	                    }
	                    e.stopPropagation();
	                    return false;

				    });

				});
			}
			
			// composite checked, will set both events		   
			function overwriteCheckedChanged($elem, rowId) {		    	
		    	var isChecked = $elem.val();	    
		    	var rowData = getRowData(rowId);	
				var agreementId = rowData.agreementId;				
				var eventSource = rowData.eventSource;				
				var eventDate = rowData.eventDate;				
				var historical = rowData.historical;				
				var trs = $jqGrid.jqGrid("getRowData");
				if (trs != "" && trs != null) {					
					for (var i=0; i<trs.length;i++) {
						if ((trs[i].workflowId !=  rowData.workflowId) && (trs[i].historical == historical) && (trs[i].eventDate == eventDate)&&(trs[i].agreementId == agreementId)&&(trs[i].eeInitTab == rowData.eeInitTab)&&(trs[i].eventSource == eventSource)&&(trs[i].isChecked!= isChecked )) {
							$('#' + trs[i].workflowId).addClass("edited");
							setCellManually(trs[i].workflowId, 'overwrite', isChecked);
							break;
						}
					}
				}
		    }
			
			
			var isSaveSuccessfull = function() {
				if(getUserData("saveWarningMsg")) {
					log(getUserData("saveWarningMsg"));
				}
							
			}
			
			//add checkBox click event
			var addChkEvent = function(){
//				var multiChks = new Array();
				$("#jqGrid tbody tr").each(function(index){
					var $multiChk = $(this).find("td:first :checkbox");
//					multiChks.push($multiChk);
					$multiChk.click(function(){
						//var numberArr = $jqGrid.jqGrid("getGridParam", "selarrrow");
						//numberArr.push($(this).attr("id"));
						
//						var checkedNum = 0;
//						$.each(multiChks, function(i, n){
//							if (n.attr('checked')) {
//								checkedNum++;
//							}
//						});

						actionBtnCheckRequest();
					});
				});
			}
			
			var showCalclateMessage = function(){
				if(getUserData("webgui.ee.dist.reg.msg")){
					log(getUserData("webgui.ee.dist.reg.msg"), false);
				}
				if(getUserData("webgui.ee.dist.msg")){
					log(getUserData("webgui.ee.dist.msg"), false);
				}
			}
			
			var updateCountsForCurrCategory = function(){
				if(isNeedFreshCountNum) {
					var currCategoryId = $("#accordions").find("div:visible").prev().attr("id");
					updateCountsByCategoryId(currCategoryId);
					isNeedFreshCountNum = false;
				}
			}
			
			var changeColor = function(data){
 				if(!data || !data.items) return;
				
				for(i=0; i<data.items.length; i++) {  
					//amended agreement
					if(data.items[i].agreementStatus==69){
       					$("#"+data.items[i].workflowId).removeClass("ui-widget-content");
           				$("#"+data.items[i].workflowId).css("border-color","#a6c9e2");
           				$("#"+data.items[i].workflowId).css("color","#aca899");
    
          			}   
					// intraDay
					var value = data.items[i].issuedValue;	                     
       				if(value) {
           				if(data.items[i].marginCallStatus==65) {
       						$("#"+data.items[i].workflowId).removeClass("ui-widget-content");
           					$("#"+data.items[i].workflowId).css("background-color","#FD823F");
           					$("#"+data.items[i].workflowId).css("border-color","#a6c9e2");  
       		   			}
       				}
       				//amended workflow
       				if(data.items[i].workflowStatus==69 || data.items[i].workflowStatus==70) {
 						$("#"+data.items[i].workflowId).removeClass("ui-widget-content");
           				$("#"+data.items[i].workflowId).css("background-color","#c1c1d1"); 
           				$("#"+data.items[i].workflowId).css("border-color","#a6c9e2");  
       		     	}	
					  
 					//historical event
 					if(data.items[i].historical ) {
 						$("#"+data.items[i].workflowId).removeClass("ui-widget-content");
           				$("#"+data.items[i].workflowId).css("background-color","#bdccda"); 
           				$("#"+data.items[i].workflowId).css("border-color","#a6c9e2");
       		     	}	 
				}
			}
			var disableFields = function(rowid, cellname, value, iRow, iCol){
			 	rowData = $jqGrid.jqGrid("getRowData",rowid);
				var UserData = getUserData(rowData.workflowId);
				if(UserData.umbrellatype==2){
					var umbrellaId = getUmbrellaId(parseInt(rowData.workflowId));
					var umbrellaData = $jqGrid.jqGrid("getRowData",umbrellaId);
					if(umbrellaData.agreementStatus==69){
						if(cellname!="marginDelvCtpy" && cellname!="cptyExposure"){
							document.getElementById(rowData.workflowId).cells[iCol].disabled = true;
					   } 
					}
				}else{
					if(rowData.agreementStatus==69 && cellname!="marginDelvCtpy" && cellname!="cptyExposure"){
						document.getElementById(rowData.workflowId).cells[iCol].disabled = true;
				   } 
				} 
			}

			$("#cb_jqGrid").click(function() {
//				if(filterId) actionBtnCheckRequest($(this).attr("checked") ? 2 : 0);
				if(itemId) actionBtnCheckRequest();
			})

			var actionBtnCheckRequest = function() {
				var selectedRowIdStr = getSelectedRowIds().toArray().join(",");
				var isAmendedAgreement = false;
				var isSameAgreement = true;
				var isHistorical = true;
				var agreementId = "";
				var statementStatus ;
				if(selectedRowIdStr){
				  for(i=0;i<selectedRowIdStr.split(",").length;i++){
					rowData = $jqGrid.jqGrid("getRowData",selectedRowIdStr.split(",")[i]);
					if(rowData.historical=="false"){
						isHistorical = false;
					}
					if(rowData.agreementStatus==69){
						isAmendedAgreement = true;
					}
					var UserData = getUserData(rowData.workflowId);
					if(UserData.umbrellatype==2){
						var umbrellaId = getUmbrellaId(parseInt(rowData.workflowId));
						var umbrellaData = $jqGrid.jqGrid("getRowData",umbrellaId);
						if(umbrellaData.agreementStatus==69){
							isAmendedAgreement = true;
						}
					}
					if(agreementId !="" && agreementId !=rowData.agreementId){
						isSameAgreement = false;
					}
					agreementId= rowData.agreementId;
					statementStatus = rowData.statementStatus;
					if(statementStatus=="<DIV>IP</DIV>"){
						statementStatus = "IP";	
				  	}
				  }
				}
				$("li", "#actions").hide();
				sendSyncRequest({
							method: 'showActionBtn',
							isAmendedAgreement:isAmendedAgreement,
							workflowId: selectedRowIdStr,
							statementStatus:statementStatus,
							isSameAgreement:isSameAgreement,
							isHistorical:isHistorical
						}, function(data){
							if (data) {
								var nameArr = data.split(",");
								for (var i = 0; i < nameArr.length; i++) {
//					                $("." + nameArr[i]).slideDown("slow");
									$("#actions").find("." + nameArr[i]).show();
								}
							}
						});
				if(!selectedRowIdStr){
					showBtnByItem(itemId);
					return ;
				}
			}


			function showBtnByItem(itemId){
				sendSyncRequest({
					method: 'showActionBtnByFilter',
					filterId:getfilterIdByItem(itemId)
				}, function(data){
					if (data) {
						var nameArr = data.split(",");
						for (var i = 0; i < nameArr.length; i++) {
							$("#actions").find("." + nameArr[i]).show();
						}
					}
				});
				
			}

			function addTreeEvent() {
				$("#jqGrid .tree-button-add").toggle(function(event) {
					
					normalEditorEscTrigger();
					
					var treeIds = ($treeIds[this.title]||[]).join(",#");
					
					if(treeIds.length != 0 && $("#"+treeIds).length != 0) {
							$("#"+treeIds).show();
					} else {
						createTrees(this);						
					}
					
					$(this).removeClass("tree-button-add").addClass("tree-button-minus");
				}, function() {
					if($treeIds[this.title].length > 0){	
						$("#"+$treeIds[this.title].join(",#")).hide();
					}	
					$(this).removeClass("tree-button-minus").addClass("tree-button-add");
					
				});
				
			}

			function createTrees(that) {

				sendSyncRequest({
					method: 'searchFundEvents',
					umEventId: that.title
				},  function(result) {
					
					var isTickAll = $("#cb_jqGrid").attr("checked");
					$treeIds[that.title] = $.map(result.items, function(data) {
						if($jqGrid.jqGrid('addRowData', data.workflowId, data, 'after', that.title)) {
							//fix select all box checked when search fund events
							if(isTickAll) $("#jqg_jqGrid_" + data.workflowId).click().attr("checked",true);
							
							changeUmbrellaColor(data,that.lang,that.language);
							return data.workflowId;
						}
					});
					
					var originalData = $jqGrid.getGridParam('userData');
			
					var newData = $.extend(originalData, result.userdata);
					
					$jqGrid.setGridParam('userData', newData);
					addChkEvent();

					addOverwriteEvent();
					
				});
			}

			var changeUmbrellaColor = function(data,agreementStatus,workflowStatus){
				//amended agreement
				if(agreementStatus==69){
   					$("#"+data.workflowId).removeClass("ui-widget-content");
       				$("#"+data.workflowId).css("border-color","#a6c9e2");
       				$("#"+data.workflowId).css("color","#aca899");
       				
      			}     

				// intraDay
				var value = data.issuedValue;	  
   				if(value||value!=0) {
       				if(data.marginCallStatus==65) {
   						$("#"+data.workflowId).removeClass("ui-widget-content");
       					$("#"+data.workflowId).css("background-color","#FD823F");
       					$("#"+data.workflowId).css("border-color","#a6c9e2");  
   		   			}
   				}
				//amended workflow
   				if(workflowStatus==69 || workflowStatus==70) {
					$("#"+data.workflowId).removeClass("ui-widget-content");
       				$("#"+data.workflowId).css("background-color","#c1c1d1"); 
       				$("#"+data.workflowId).css("border-color","#a6c9e2");  
   		     	}	 
				//historical event
				if(data.historical ) {
					$("#"+data.workflowId).removeClass("ui-widget-content");
       				$("#"+data.workflowId).css("background-color","#bdccda");
       				$("#"+data.workflowId).css("border-color","#a6c9e2"); 
   		     	}	 
			}
			
			
			var commentsFun = function(savedType){
                sendSyncRequest({
                    method: 'saveComments',
                    savedType: savedType,
                    workflowId: rowData.workflowId,
                    eeComments: $("#txtComments").val()
                
                });
                $("#dialog-comments").dialog('close');
                
				multiEditorEnterTrigger($("#txtComments").val());
				
            }

			//	save comments
            $("#dialog-comments").dialog({
                autoOpen: false,
                height: 250,
                width: 380,
                modal: true,
                buttons: {
                    'Save': function() {
						commentsFun('COMMENT_ONLY');
						
					},
                    'Save to Disputes': function(){
						commentsFun('COMMENT_AND_DISPUTE');
						
                    },
                    'Save to Notes': function(){
                        commentsFun('COMMENT_AND_NOTE');
                        
                    }
                }
            
            });
			
			//	currencyExchange
			$("#dialog-ccyExchange").dialog({
				autoOpen: false,
				height: 230,
				width: 350,
				show: 'scale',
				hide: 'explode',
				buttons: {
					'convert': function() {
					
						sendSyncRequest({	
								method: 'ccyConvertor',
								originalCurrency: $("select[name='originalCurrency']").val(),
								originalAmount: $("#_originalAmount").val(),
								resultCurrency: $("select[name='resultCurrency']").val() 
						}, function(data){	
                   			if(data=="Change rate is wrong"||data=="OriginalAmount is invalid"){
                   				$("#errorMsg").text(data);
                   			}else{
								$("#dialog-ccyExchange").dialog('close');
//                   				$jqGrid.setCell(rowData.workflowId,"marginDelvCtpy",data);
								
								multiEditorEnterTrigger(data);
                   			}                		
						});
					},
					'close': function() {
						$multiEditor.focus();
						$(this).dialog('close');
					}
				
				}
				
			});

			function editFocusTrigger($elem) {
				//fix custom_value bug
				$normalEditor = $elem;
				
				window.setTimeout(function () { $elem.focus();}, 0);
			}
			
			function multiEditorEnterTrigger(data) {
				$multiEditor.val(data);
				var evt = jQuery.Event("keydown");
				evt.keyCode = $.ui.keyCode.ENTER;
				$multiEditor.trigger(evt);
			}
			
			function normalEditorEscTrigger() {
				var evt = jQuery.Event("keydown");
				//evt.keyCode = $.ui.keyCode.ESCAPE;
				evt.keyCode = $.ui.keyCode.ENTER;
				if($normalEditor && $normalEditor.length > 0) {
					$normalEditor.trigger(evt);
				}
			}

			function isFlipped(eventId){
				var isFlipped;
				sendSyncRequest({	
					method: 'isFlippedEvent',
					workflowId: eventId
				}, function(data){
					isFlipped = data;
				},"", "", true);
				return isFlipped;
			}

			
			function isLess(marginDelvCtpy,marginCall){
				var isless;
				sendSyncRequest({	
					method: 'isLessThan',
					marginDelvCtpy: marginDelvCtpy,
					marginCall:marginCall
				}, function(data){
					isless = data;
				},"", "", true);
				return isless;
			}

			function isGreater(marginDelvCtpy,marginCall){
				var isgreater;
				sendSyncRequest({	
					method: 'isGreaterThan',
					marginDelvCtpy: marginDelvCtpy,
					marginCall:marginCall
				}, function(data){
					isgreater = data;
				},"", "", true);
				return isgreater;
			}
			
			
			function checkForComment(changedArr) {
				var failureRows = new Array();
				var workflowData;
				$.each(changedArr, function(index, val) {
					workflowData = getRowData(val.id);
					
					//check whether the comments are changed
					if(workflowData.comments) {
						return true;
					}
					
					//check margin call status whether is 'waived' or 'Full Dispute' or 'Partial Dispute'
					if(val.marginCallStatus == "Waived" || val.marginCallStatus == "Full Dispute" || val.marginCallStatus == "Partial Dispute") {
						failureRows.push(val.id);
						return true;
					}
					
					//check max value between 'Agreement Requirement' and 'Counterparty Amount'	marginCallStatus 
					if(<c:out value="${isMandatoryComment}"/>) {

						if(!val.marginDelvCtpy && workflowData.marginDelvCtpy.replace(",",".")=="0.00"){
							return true;
						}
						if(!val.marginDelvCtpy && tempComments[rowData.workflowId]==workflowData.comments){
							return true;
						}
						if(workflowData.movementRequiredId == 51 || workflowData.movementRequiredId == 52) {
							if(isLess(workflowData.marginDelvCtpy,workflowData.marginCall)=="true") {
								failureRows.push(val.id);
							}
							
						} else if(workflowData.movementRequiredId == 53 || workflowData.movementRequiredId == 54) {
							if(isGreater(workflowData.marginDelvCtpy,workflowData.marginCall)=="true") {
								failureRows.push(val.id);
							}
						
						}
					}
					
				});

				return failureRows;
			}

			function getSelectedAgrId(obj){
				var agrId = new Array();
				var wfId = new Array();
				var selectedRowIds = $jqGrid.jqGrid("getGridParam", "selarrrow");
				if(!selectedRowIds) {
					selectedRowIds = getSelectedRowIds();	
				}
				for (var i = 0; i < obj.length; i++) {
					for(j=0;j<selectedRowIds.length;j++){
				 		if(obj[i] == selectedRowIds[j]){
				 			wfId.push(obj[i]);
					}
				  }
			    }
				for (var j = 0; j < wfId.length; j++) {
					var curRowData = $jqGrid.jqGrid("getRowData", wfId[j]);
					agrId.push(curRowData.agreementId);
				}
				return agrId;
			}

			function getAgrId(obj){
				var agrId = new Array();
				for (var j = 0; j < obj.length; j++) {
					var curRowData = $jqGrid.jqGrid("getRowData", obj[j]);
					agrId.push(curRowData.agreementId);
				}
				return agrId;
			}
			
			// show warning msg when std type is exposure with some especilly status
			function exposureStdChecked(eventId, checkedCategory){
				var flag;
				var hasWarning = true;
				var workflowData = getRowData(eventId);
				var userData = getUserData(eventId);

				var isHistoric = workflowData.historical == "true";
				var isIssued = workflowData.issuedValue != "";
				
				if(workflowData.overwrite == "true"){
					return;
				}

				//when Priciple favor, do not need calculator
				var pricipleFavor  = isLess(workflowData.marginCall, workflowData.marginDelvCtpy)=="true";
				var pricipleNotFavor = isLess(workflowData.marginDelvCtpy , workflowData.marginCall)=="true";

				
				//workflowData.marginDelvCtpy equals workflowData.marginCall, do not need warning msg
				if(pricipleFavor || (!pricipleFavor^pricipleNotFavor)){
					return;
				}
				if(userData.stdType == 401) {
					if(hasWarning && isHistoric && (checkedCategory == "historic" || checkedCategory == null)){
						alert("Please note that a new event has been generated. The STD will calculate based on the current statement values");
						hasWarning = false;
						flag = true;
					}
					
					if(isNaN(parseInt(workflowData.cptyExposure))
							&& anotherEventExposureIsNull(eventId)
							&& (checkedCategory == "exposureNotNull" || checkedCategory == null)) {					
						flag = window.confirm("The Counterparty Exposure Amount has not been provided. Without this value the Exposure STD calculation cannot take place. Would you like to proceed?");
					}
				}
				return flag;
			}
			//if an event is composite type, it check an other exposure is null. if has not another, will return true
			function anotherEventExposureIsNull(rowId){					    	    
		    	var rowData = getRowData(rowId);	
				var agreementId = rowData.agreementId;				
				var eventSource = rowData.eventSource;				
				var eventDate = rowData.eventDate;				
				var historical = rowData.historical;				
				var trs = $jqGrid.jqGrid("getRowData");
				if (trs != "" && trs != null) {					
					for (var i=0; i<trs.length;i++) {
						if ((trs[i].workflowId !=  rowData.workflowId) 
								&&(trs[i].historical == historical) 
								&&(trs[i].eventDate == eventDate)
								&&(trs[i].agreementId == agreementId)
								&&(trs[i].eeInitTab == rowData.eeInitTab)
								&&(trs[i].eventSource == eventSource)) {
										
							return isNaN(parseInt(trs[i].cptyExposure));							
						}
					}
				}
				return true;
		    }

			function allExposureStdChecked(){
				var changedArr = $jqGrid.jqGrid('getChangedCells','dirty');
				$jqGrid.jqGrid("appendPostData", {changedArr: JSON.stringify(changedArr)});
				eventIds = getChangedUmbrellaIds(changedArr);
				for(var i = 0; i<eventIds.length; i++ ){
					var flag = exposureStdChecked(eventIds[i]);						
				
					if(isNaN(flag)){
						continue;
					}else if(flag){													
						break;	
					}else{
						return false;											
					}					
				}
				return true;
			}

			//check the historic STD Exposure event
			function stdHistoricCheck(eventIds){
				for(var i = 0; i<eventIds.length; i++ ){
					var flag = exposureStdChecked(eventIds[i], "historic");		
					//the warning msg show only once
					if(flag){		
						break;													
					}						
				}			
			}

			//get all changed events id 
			function getChangedEventIds(changedArr){
				var eventIds = new Array();
				$.each(changedArr, function(index, value) {					
					var eventId = parseFloat(value.id);
					eventIds.push(eventId);
				});
				return eventIds;
			}
			
			// add action event
			$("li","#actions").click(function() {
				normalEditorEscTrigger();
				
				var selectedEvtIds = getSelectedRowIds();
				var rows;
				var changedArr = $jqGrid.jqGrid('getChangedCells','dirty');
				if($(this).hasClass("save")) {
					var eventIds;
					rows = checkForComment(changedArr);
					if(rows.length>0){
			            alert("Comments must be populated");
			        	return;
			        }
					
					isNeedFreshCountNum = true;
					
					//$jqGrid.jqGrid("getPostData");
					$jqGrid.jqGrid("appendPostData", {changedArr: JSON.stringify(changedArr)});
					
					eventIds = getChangedEventIds(changedArr);
					
					stdHistoricCheck(eventIds);
					
					for(var i = 0; i<eventIds.length; i++ ){
						var flag = exposureStdChecked(eventIds[i], "exposureNotNull");		
						//the warning msg show only once
						if(isNaN(flag)){
							continue;
						}else if(!flag){													
							return;
						}else{
							break;													
						}						
					}					

					eventIds = getChangedUmbrellaIds(changedArr);
					$jqGrid.jqGrid("appendPostData", {eventIds: eventIds.join(",")});
					
					$jqGrid.trigger("reloadGrid");
					$jqGrid.jqGrid("removePostDataItem", "changedArr");
					$jqGrid.jqGrid("removePostDataItem", "eventIds");
					
					$("li", "#actions").hide();
					showBtnByItem(itemId);
				} else if($(this).hasClass("populateCtpyAmt")) {
					
					var umbrellaAmtArr = new Array();
					
					$.each(selectedEvtIds, function(index, value) {
						
						var umRowData = getRowData(value);
						var userData = getUserData(value);
						
						//normal event
						if (userData.umbrellatype == 0) {
							if(parseInt(umRowData["marginDelvCtpy"]) == 0 || isNaN(parseInt(umRowData["marginDelvCtpy"]))) {
								$('#' + value).addClass("edited");

								var umbrellaActionId = umRowData["movementRequiredId"];
								var umbrellaAmtValue = umRowData["agreedAmount"];
								// convert sys calculate amount to negative when movement is Delivery/Return
								if(umbrellaActionId == 53 || umbrellaActionId == 54) {
									//system calculate amount always positive
									umbrellaAmtValue = "-" + umbrellaAmtValue;
								}
								setCellManually(value, 'marginDelvCtpy', umbrellaAmtValue);
								setCellManually(value, 'marginDelvCtpyUmbBaseCcy', umbrellaAmtValue);

							}
							
						} else if (userData.umbrellatype == 1) {
							if (!$treeIds[value]) {
								log("Please expand the sub-agreements before auto-populating the counterparty amount");
								return;
							}
							
							var umbrellaAmt = new Object();
							var fundAmts = new Array();
							
							$.each($treeIds[value], function(index, elem){
								var fundRowData = getRowData(elem);
								
								var fundAmt = new Object();
								fundAmt.workflowId = elem;
								fundAmt.amtValue = fundRowData["agreedAmount"];
								fundAmt.amtValue2 = fundRowData["marginDelvCtpy"];
								fundAmt.currency = getUserData(elem).agrBaseCcy;
								fundAmt.actionId = fundRowData["movementRequiredId"];
								fundAmt.changed = true;
								
								// convert sys calculate amount to negative when movement is Delivery/Return
								if(fundAmt.actionId == 53 || fundAmt.actionId == 54) {
									//system calculate amount always positive
									fundAmt.amtValue = "-" + fundAmt.amtValue;
								}
								
								fundAmts.push(fundAmt);
								
								if (parseInt(fundAmt.amtValue2) == 0) {
									$('#' + elem).addClass("edited");
									setCellManually(elem, 'marginDelvCtpy', fundAmt.amtValue);
								}
								
							});
							umbrellaAmt.workflowId = value;
							umbrellaAmt.marketDataId = umRowData.marketDataId;
							umbrellaAmt.currency = getUserData(value).agrBaseCcy;
							umbrellaAmt.funds = fundAmts;
							umbrellaAmtArr.push(umbrellaAmt);
								
						} else if (userData.umbrellatype == 2) {
							var curUmbrellaId = getUmbrellaId(parseInt(value));
							//only ticked the fund event but not ticked the umbrella event
							if ($.inArray(curUmbrellaId+"", selectedEvtIds) === -1) {
								
								var umbrellaAmt = new Object();
								var fundAmts = new Array();
								
								$.each($treeIds[curUmbrellaId], function(index, elem){
									var fundRowData = getRowData(elem);
									
									var fundAmt = new Object();
									fundAmt.workflowId = elem;
									fundAmt.amtValue = fundRowData["agreedAmount"];
									fundAmt.amtValue2 = fundRowData["marginDelvCtpy"];
									fundAmt.currency = getUserData(elem).agrBaseCcy;
									fundAmt.actionId = fundRowData["movementRequiredId"];
									if(elem == value) fundAmt.changed = true;
									
									// convert sys calculate amount to negative when movement is Delivery/Return
									if(fundAmt.actionId == 53 || fundAmt.actionId == 54) {
										//system calculate amount always positive
										fundAmt.amtValue = "-" + fundAmt.amtValue;
									}
									fundAmts.push(fundAmt);
									
									if (elem == value && parseInt(fundAmt.amtValue2) == 0) {
										$('#' + elem).addClass("edited");
										setCellManually(elem, 'marginDelvCtpy', fundAmt.amtValue);
									}
									
								});
								umbrellaAmt.workflowId = curUmbrellaId;
								umbrellaAmt.marketDataId = umRowData.marketDataId;
								umbrellaAmt.currency = getUserData(curUmbrellaId).agrBaseCcy;
								umbrellaAmt.funds = fundAmts;
								
								umbrellaAmtArr.push(umbrellaAmt);
							}
						}
					});
					
					if(umbrellaAmtArr.length > 0) {
						sendSyncRequest({	
							method: 'getUmbrellaCcyCtpyAmts',
							umbrellaAmtArr:  JSON.stringify(umbrellaAmtArr)
						}, function(data){
							$.each(data, function(index, elem) {
								
								if(elem.funds.length > 0) {
									$('#' + elem.workflowId).addClass("edited");
									setCellManually(elem.workflowId, 'marginDelvCtpy', elem.amtValue);
									setCellManually(elem.workflowId, 'marginDelvCtpyUmbBaseCcy', elem.amtValue);
									
									
									for(var i=0; i<elem.funds.length; i++) {
										setCellManually(elem.funds[i]["workflowId"], 'marginDelvCtpyUmbBaseCcy', elem.funds[i]["amtValue"]);
									}
								}
								
							});
						});

					}
					
				} else if($(this).hasClass("populateRelveCtpyAmt")) {
					var umbrellaId = selectedEvtIds[0];
					var fundAmts = new Array();
					if(!$treeIds[umbrellaId]) {
						log("Please expand the sub-agreements before auto-populating the counterparty amount");
						return;
					}
					
					var umRowData = getRowData(umbrellaId);
					var actionStatus = umRowData["movementRequired"];
					if( actionStatus.indexOf("No Calls") != -1){
					    log('Can not auto populate counterparty amount as requirement amount is 0.');
					    return;
					}
					$.each($treeIds[umbrellaId], function(index, elem) {
						var fundRowData = getRowData(elem);
						
						var fundAmt = new Object();
						fundAmt.workflowId = elem;
						fundAmt.amtValue = fundRowData["agreedAmount"];
						fundAmt.currency = getUserData(elem).agrBaseCcy;
						fundAmt.actionId = fundRowData["movementRequiredId"];
						
						// convert sys calculate amount to negative when movement is Delivery/Return
						if(fundAmt.actionId == 53 || fundAmt.actionId == 54) {
							//system calculate amount always positive
							fundAmt.amtValue = "-" + fundAmt.amtValue;
						}
						fundAmts.push(fundAmt);
						
					});

					var umbrellaSysCalcAmt = umRowData["agreedAmount"];
					var umbrellaActionId = umRowData["movementRequiredId"];
					if(umbrellaActionId == 53 || umbrellaActionId == 54) {
						umbrellaSysCalcAmt = "-" + umbrellaSysCalcAmt;
					}
					
					sendSyncRequest({	
						method: 'relativeApplyOutput',
						inputedAmt: umRowData["marginDelvCtpy"],
						umbrellaSysCalcAmt: umbrellaSysCalcAmt,
						umbrellaCcy: getUserData(umbrellaId).agrBaseCcy,
						marketDataId: umRowData.marketDataId,
						agreementId: umRowData["agreementId"],
						fundAmts:  JSON.stringify(fundAmts)
						
					}, function(data){
						setCellManually(umbrellaId, 'marginDelvCtpy', data["totalAmt"]);
						setCellManually(umbrellaId, 'marginDelvCtpyUmbBaseCcy', data["totalAmt"]);
						
						$.each(data.fundValues, function(index, elem) {
							$('#' + elem["workflowId"]).addClass("edited");
							setCellManually(elem["workflowId"], 'marginDelvCtpy', elem["amtValue"]);
							setCellManually(elem["workflowId"], 'marginDelvCtpyUmbBaseCcy', elem["amtValue2"]);
						});
						
					});
					
				} else if($(this).hasClass("autoemail")||$(this).hasClass("autoEmailPartialSet")||$(this).hasClass("allemail")) {
					var isEmailAll = false;
					var isPartialSet = false;
					var URL = $(this).attr("baseURL")+"?";
					var methodName = 'sendAutoEmail';
					
					if($(this).hasClass("allemail")) {
						isEmailAll = true;
					} else if($(this).hasClass("autoEmailPartialSet")) {
						isPartialSet = true;
					}
					
					rows = checkForComment(changedArr);
					var message = "";
					if(isEmailAll) {
						rows = getAgrId(rows);
					} else {
						rows = getSelectedAgrId(rows);
					}
					if(rows.length>0){
						for (var i = 0; i < rows.length; i++) {
							message = message+rows[i]+",";
						}
						message = message.substring(0,message.length-1);
						alert("Comments must be populated.");
						log("Comments must be populated for the following agreements: "+message, false);
			        	return;
					}
					
					if(isEmailAll) {
						URL = buildURLAll(URL,$(this).attr("param"));
						methodName = "sendBatchLetter";
					} else {
						URL = buildMultipleSelectedURL(URL, $(this).attr("param"));
					}
					
					sendSyncRequest({
						method: methodName,
						changedArr:JSON.stringify(changedArr),
						eventIds: getChangedUmbrellaIds(changedArr).join(","),
						isPartialSet: isPartialSet
					}, function(data){
                		triggerToolbarSearch();
                	}, 'json', parseUrlWithWinName(URL));
					
					blockUI();
				} else {
				
					var baseURL =  $(this).attr("baseURL");
					var parameter = $(this).attr("param");
					
					var URL = baseURL;
					
					if($(this).hasClass("transfer")) {
						if(parameter){
							URL = baseURL+"?";
							URL = buildURL(URL,parameter);
						}
						 $dialogtransfer.load(parseUrlWithWinName(URL), function(){
							 $dialogtransfer.dialog('open');
						 }); 

					} else if($(this).hasClass("bulkBooking")) {
						rows = checkForComment(changedArr);
						if(rows.length>0){
							alert("Comments must be populated");
							return;
						}else{	
							sendSyncRequest({	
								method: 'saveDataBeforeAction',
								changedArr:JSON.stringify(changedArr),
								eventIds: getChangedUmbrellaIds(changedArr).join(",")
							}, null ,"","", true);
						
							isFlippedEvent(baseURL, parameter, "bulkBooking");
						}
						//if(parameter){
						//	URL = baseURL+"?";
						//	URL = buildURL(URL,parameter);
						//}
						//$dialogbook.load(parseUrlWithWinName(URL), function(){
						//	$dialogbook.dialog('open');
						// }); 
						
					} else if($(this).hasClass("selectedbookcash")){
						if(parameter){
							URL = baseURL+"?";
							URL = buildMultipleSelectedURL(URL,parameter);
						}
						redirectWithTabId("/firmament/" + URL);
					}else if($(this).hasClass("instrumentBooking")){

										
						sendSyncRequest({	
							method: 'saveDataBeforeAction',
							changedArr:JSON.stringify(changedArr),
							eventIds: getChangedUmbrellaIds(changedArr).join(",")
						}, null ,"","", true);
					
						isFlippedEvent(baseURL, parameter, "instrumentBooking");
						//createInstrument();						
						
					}else if($(this).hasClass("bookcash")){
						URL = baseURL+"?";
					 	URL = buildURLAll(URL,parameter);
					 	redirectWithTabId("/firmament/" + URL);
					} else {
						var waitSyncData = false;
						if(!$(this).hasClass("showemaillog")){
							rows = checkForComment(changedArr);
							if(rows.length>0){
								alert("Comments must be populated");
								if($(this).hasClass("createletter")||$(this).hasClass("bookasset")){
									return;
								}
							}else{	
								if($(this).hasClass("instrumentBooking")||$(this).hasClass("bookasset")){
									sendSyncRequest({	
										method: 'saveDataBeforeAction',
										changedArr:JSON.stringify(changedArr),
										eventIds: getChangedUmbrellaIds(changedArr).join(",")
									},	null ,"","", true);
									//});
									isFlippedEvent(baseURL, parameter, false);
									waitSyncData = true;
								}else{
									sendSyncRequest({	
										method: 'saveDataBeforeAction',
										changedArr:JSON.stringify(changedArr),
										eventIds: getChangedUmbrellaIds(changedArr).join(",")
									});									
								}
							}
						}
						if(waitSyncData){
							return;
						}						
						if(parameter){
							URL = baseURL+"?";
							URL = buildURL(URL,parameter);
						}						
		    		    redirectWithTabId("/firmament/" + URL);
					}
				
				}  
			});
						
			//  checked the LogicAction type
			function isFlippedEvent(baseURL, parameter, loadDialog){

				var RowIds = getSelectedRowIds().toArray();
				var rowdata = $jqGrid.jqGrid("getRowData", RowIds[0]);
				var rowdata = getRowData(RowIds[0]);				

				var eventId = rowData.workflowId;
				var umbrellaId = getUmbrellaId(parseInt(eventId)); 
								
				if(isFlipped(eventId) != "false"){
					alert("The implied booking is in the opposite direction to the event. This booking cannot be made.");	
					$jqGrid.trigger("reloadGrid");				
					return false;
				}
				
				if(parameter){
					URL = baseURL+"?";
					URL = buildURL(URL,parameter);
				}

				if(loadDialog == "bulkBooking"){
					$dialogbook.load(parseUrlWithWinName(URL), function(){
						$dialogbook.dialog('open');
					 }); 
					
				}else if(loadDialog == "instrumentBooking"){
					createInstrument();
					
				}else{
					 redirectWithTabId("/firmament/" + URL);
				}

				//$jqGrid.trigger("reloadGrid");
				//jQuery("#"+umbrellaId).find(".tree-button-add").click();
				//$("#jqg_jqGrid_" + eventId).click().attr("checked",true);				
				 
				return;				
			}

			
			function buildURLAll(URL, parameter){
				var paraName="";
				var paraValue="";
				var append = true;
				var $obj = $(":text, select","#p4 .ui-search-toolbar");	
				$obj.each(function(i) {		
					URL=URL+$(this).attr("id")+"="+$(this).val()+"&";              							
				});
				$("#"+getfilterIdByItem(itemId)).siblings(":input").each(function(i){
					paraName = $(this).attr("name");
					paraValue = $(this).val();
					$obj.each(function(i) {		
						if("gs_"+paraName==$(this).attr("id")){
							append = false;
						}               							
					});
					if(append){
						URL=URL+paraName+"="+paraValue+"&";
					}
				});
				
				URL=URL+"isNew=New";
				return URL;
			}
			
			function buildMultipleSelectedURL(URL, parameter){
				var curRowData;
				var str;
				var parastr;
				var selectedRowIds = $jqGrid.jqGrid("getGridParam", "selarrrow");
				if(!selectedRowIds) {
					selectedRowIds = getSelectedRowIds();
					
				}
				str = parameter.split(",");
				
				for (i=0;i<str.length;i++ ){
					var paravalue="";
					for(j=0;j<selectedRowIds.length;j++){
					 	curRowData = $jqGrid.jqGrid("getRowData", selectedRowIds[j]);
					 	
						if(str[i].indexOf("=")!= -1) {
							if(parastr!=str[i]){
								URL = URL + str[i];
								parastr=str[i];
							}
						
						} else {
	        				//URL = URL + str[i] + "=" + getParamValue(curRowData, str[i]) + "&";
	        				paravalue = paravalue+ getParamValue(curRowData, str[i])+",";
						}
	    		  	}
    		  	
	    		  	if(paravalue!=""){
	    		  		paravalue = paravalue.substring(0,paravalue.length-1);
	    		  		URL = URL+ str[i] + "="+paravalue+"&";
	    		  	}
    		  	}
    		    URL = URL.substring(0,URL.length-1);
    		   
    		    return URL;
			}

			function buildURL(URL, parameter){
				var selectedRowIds = $jqGrid.jqGrid("getGridParam", "selarrrow");
				if(!selectedRowIds || selectedRowIds.length == 0) {
					selectedRowIds = getSelectedRowIds();
					
				}
				var curRowData = $jqGrid.jqGrid("getRowData", selectedRowIds[0]);
				
				var str = parameter.split(",");
				
				for (i=0;i<str.length;i++ ){   
					if(str[i].indexOf("=") != -1) {
						URL = URL + str[i] + "&";
					} else {
        				URL = URL + str[i] + "=" + getParamValue(curRowData, str[i]) + "&";
					}
    		  	}
    		    URL = URL.substring(0,URL.length-1);
    		    return URL;
			}

			function getSelectedRowIds() {
				return $("td:first :checkbox", "#jqGrid  tbody tr").filter(":checked").map(function() {
				 	return $(this).attr("id").replace("jqg_jqGrid_","");
				 });
			}
			
			function getMergedParamObj() {
				var searchFilter = new Object();
				var bindFilter = new Object();
				
				$(":text, select","#p4 .ui-search-toolbar").each(function() {
					searchFilter[$(this).attr("id").replace("gs_", "")] = $(this).val();
				}); 

				$("#"+getfilterIdByItem(itemId)).siblings(":input").each(function(i){
					bindFilter[$(this).attr("name")] = $(this).val();
				});
				
				return $.extend(bindFilter, searchFilter);
			}
			
			function getMergedParamStr() {
				return $.param(getMergedParamObj());
			}

			function getParamValue(obj, paramName) {
				return obj[paramName];
				
			}
	
// West Navigation
/*
			jQuery("#accordions")
.append('<h3 id="f3" title="Last Filters"><a href="#">Last Filters</a><span class="ui-icon ui-icon-plusthick" style="left:9em"></span>
<span class="ui-icon ui-icon-pencil" style="left:10em"></span><span class="ui-icon ui-icon-closethick" style="left:11em"></span></h3>')
.accordion("destroy")
.accordion({ fillSpace:true })
.accordion("resize")
			*/
			
			// ** Setup Accordion
			$accordions = $("#accordions").accordion({
				fillSpace: true
			});
	
			// ** Setting Sortable
			var $sortableItems = $accordions.find(".connectedSortable").sortable({
				appendTo: 'body', 
				cursor: 'move',
				placeholder: 'ui-sortable-placeholder-item',
				helper: function(event) {
					return $('<div class="ui-icon ui-icon-circle-check"></div>');
				},
				//stop: saveLayout,
			    opacity: 0.5   
			}).disableSelection();
			
			// ** save item order
			$("#saveOrderBtn").click(saveLayout);
			function saveLayout() { 
				
				var idsArr = new Array();			
				$sortableItems.each(function(i) {
					var idArr = $(this).find("li").map(function(index, item) {		
						return $(item).attr("id");
					})
					idsArr.push(idArr.get());
				})
				
				sendSyncRequest({	
					method: 'updateItemPos',
					cfgId: cfgId,
					idsArray: JSON.stringify(idsArr)
				}, function(data){
                   cfgId = data;
                });
			}
			
			// ** drag item on accordion header
			var $accordion_headers = $("#accordions > h3");
			$accordion_headers.not("#default").droppable({
				accept: "#accordions .connectedSortable li",
				hoverClass: "ui-state-highlight",
				drop: function(ev, ui) {
					var $item = $(this);
					var $list = $item.next("div").find('.connectedSortable');
	
					ui.draggable.css("display", "");
					ui.draggable.hide('slow', function() {
						$accordions.accordion( "activate" , $accordion_headers.index($item) );
						//be care of $(this), this --> draggable item
						$(this).appendTo($list).show('highlight', 2000);
					});
				}
			});

			// ** add category add, edit, del hover
			$accordion_headers.not("#default").hover(function() {
				$(this).find("a").nextAll().show();
			}, function() {
				$(this).find("a").nextAll().hide();
			}).find("a").nextAll().click(function() {
				$selectedCategory = $(this).parent();
				if ($(this).hasClass("ui-icon-plusthick")) {
					clearValidationStatus();					
					
					$("#itemLabel").val("");
					$("#itemDesc").val("");
					$("#copyfilter").show();
					$("#copyFilterLable").show();
					$("#copyfilter").val("");
					$dialogitem.dialog( "option", "title", 'New Item' );
					$dialogitem.dialog( "option", "buttons", { "Save": addItemDialogFun, "Cancel": cancelDialogFun } );
					
					$dialogitem.dialog('open');
				} else if ($(this).hasClass("ui-icon-pencil")) {
					clearValidationStatus();
					
					$("#categoryLabel").val($selectedCategory.find("a").text());
					$("#categoryDesc").val($selectedCategory.attr("title"));
					
					$dialogcategory.dialog( "option", "title", 'Category Edit' );
					$dialogcategory.dialog( "option", "buttons", { "Save": editCategoryDialogFun, "Cancel": cancelDialogFun } );
 					$dialogcategory.dialog('open');
					
				} else {

					if($selectedCategory.next().children('ul').children().length == 0) {
						$dialogConfirm.dialog( "option", "title", 'Category Delete' );
						$dialogConfirm.dialog( "option", "buttons", { "Delete": delCategoryDialogFun, "Cancel": cancelDialogFun } );
						$dialogConfirm.dialog('open');	
					} else {
						alert("please delete items belong to category first");
					}
				}
				return false;
			});
			
			function clearValidationStatus() {
				$("form.validationform .status").html("&nbsp;").removeClass("checked");
			}
			
			function createInstrument(){
				$("#errorInstrument").text("");
				$("#instrumentId").val("");
				$dialogInstrumentId.dialog( "option", "title", 'Instrument Id' );
				$dialogInstrumentId.dialog( "option", "buttons", { "OK": createInstrumentFun, "Cancel": cancelDialogFun } );
				$dialogInstrumentId.dialog('open');
			}
			// ** add item edit & del behavior
			bindDefaultFilterItemEvent($(".sysFilterItems li", "#accordions"));
			bindFilterItemEvent($(".connectedSortable li", "#accordions"));
			
			// ** Accordion Item Click Event
			function bindDefaultFilterItemEvent(obj) {
				obj.hover(function() {
					$(this).addClass("item-hover");
				}, function() {
					$(this).removeClass("item-hover")
				}).click(itemClickFun);
			}
			
			function bindFilterItemEvent(obj) {
				obj.hover(function() {
					$(this).addClass("item-hover").find("a").show();
				}, function() {
					$(this).removeClass("item-hover").find("a").hide();
				}).click(itemClickFun)
					.find("a").click(itemModifiedFun);
			}
			
			function itemClickFun() {
				
				$(this).addClass("item-click").siblings().removeClass("item-click");
				
				checkGridStatus();
				clearToolbarValue();
//				clearDataFilter();
				
				itemId = $(this).attr("id");
				
				$(this).find("input:hidden").each(function(i) {
					
					$("#gs_"+$(this).attr("name")).val($(this).val());
				});
				
				checkMorePostData(this, "fromColMgr");
				checkMorePostData(this, "tabPage");
				checkMorePostData(this, "actionType");
				checkMorePostData(this, "subAction");
				checkMorePostData(this, "callStatus");
				checkMorePostData(this, "multiOrder");
				 //added by Oliver
                sortColumns();

				
				$("li", "#actions").hide();
				showBtnByItem(itemId);
				
			}
            //this flag is to mark if the ic
            var iconsIsHidden=false;
            /**
            *This function sorts the order of columns and hide the columns which are defined as hidden.
            * @Author: Oliver Zhang
            */
            function sortColumns() {
                var colModel = $jqGrid.jqGrid("getGridParam", "colModel");
                var currentColum = [];
                var currentHiddenIds=[];
                $(colModel).each(function(index) {
                    currentColum[index] = colModel[index].name;
                    if (colModel[index].hidden) {
                        currentHiddenIds[currentHiddenIds.length] = colModel[index].name;
                    }
                });
                sendSyncRequest({
                            method: 'getColumnSetting',
                            cfgId:cfgId,
                            columnSettingId: $('#' + itemId).attr("columnsetting")
                        }, function(data) {
                            //ajust the column order by adding 1 for each
                            var userColumnNames = [];
                            var columnOrder = [];
                            //all the columns always starts with a checkbox which is named 'cb'
                            userColumnNames[0] = 'cb';
                            for (var a = 0; a < data.order.length; a++) {
                                userColumnNames[a + 1] = DEFAULT_COLUMN_ORDER[data.order[a]];
                            }
                            //extracting the column names which should be hidden.
                            var hiddenColumns = [];
                            for (var b = 0; b < data.hiddenItems.length; b++) {
                                hiddenColumns[b] = DEFAULT_COLUMN_ORDER[data.hiddenItems[b]];
                            }
                            // get the  relative order by comparing with current column order in grid.
                            for (var c = 0; c < userColumnNames.length; c++) {
                                for (var d = 0; d < currentColum.length; d++) {
                                    if (userColumnNames[c] == currentColum[d]) {
                                        columnOrder[c] = d;
                                        break;
                                    }
                                }
                            }
                            $jqGrid.remapColumns(columnOrder, true);
                            $jqGrid.showCol(DEFAULT_COLUMN_ORDER);
                            $jqGrid.hideCol(hiddenColumns);
                            $jqGrid.jqGrid('setGridParam',{sortname:data.sortName,sortorder:data.sortOrder});
                            $("span.s-ico", $jqGrid[0].grid.hDiv).hide();
                            iconsIsHidden=true;
                            triggerToolbarSearch();
                        }
                );
            }
            
			function itemModifiedFun() {
			
				$selectedItem = $(this).parent();
				if($(this).hasClass("pencil")) {
					clearValidationStatus();
					
					$("#copyfilter").hide();
					$("#copyFilterLable").hide();
					$selectedItem.removeClass("ui-state-default");
					$sysIcons.find("li").removeClass("ui-selected").each(function(i) {
						if($(this).attr("title") == $selectedItem.attr("class")) {
							$(this).addClass("ui-selected");
							return false;
						}
					});

					$("#itemLabel").val($selectedItem.find("font").text());
					$("#itemDesc").val($selectedItem.attr("title"));
					
					$dialogitem.dialog( "option", "title", 'Item Edit' );
					$dialogitem.dialog( "option", "buttons", { "Save": editItemDialogFun, "Cancel": cancelDialogFun } );
//					$dialogitem.dialog( "option", "buttons", [ { text: "Save", click: editItemDialogFun }, { text: "Cancel", click: cancelDialogFun } ] );
					$dialogitem.dialog('open');
				} else {
					$dialogConfirm.dialog( "option", "title", 'Item Delete' );
					$dialogConfirm.dialog( "option", "buttons", { "Delete": delItemDialogFun, "Cancel": cancelDialogFun } );
//					$dialogConfirm.dialog( "option", "buttons", [ { text: "Delete", click: delItemDialogFun }, { text: "Cancel", click: cancelDialogFun } ] );
					$dialogConfirm.dialog('open');
				}
				return false;
				
			}
			
			function checkMorePostData(item, pname) {
				var pval = $(item).find("input[name='" + pname + "']").val();
				var obj = {};
				if(pval) {
					obj[pname] = pval;
					$jqGrid.jqGrid("appendPostData", obj);
				} else {
					$jqGrid.jqGrid("removePostDataItem", pname);
					
				}
			}
			
			function clearToolbarValue() {
				
				$(".ui-search-toolbar :text","#p4").each(function(i) {
					$(this).val("");
				});
				
				$(".ui-search-toolbar select", "#p4").each(function(i) {
					$(this).get(0).selectedIndex=0;
					
//					$(this).find("option").each(function(index) {
//						if(index===0) { this.selected = true; }
//					});
					
				});
				
			} 

			var cancelDialogFun = function() {
				$(this).dialog('close');
			}
			
			var addCategoryDialogFun = function() {
				
			}

			var createInstrumentFun = function() {
                /**
                 *This method is upgraded by Oliver, in which the instrument id is returned with market,
                 * but olny instrument id should be passed to the ajax function
                 */
				var idWithMarket= $("#instrumentId").val();
				if(idWithMarket.length==0){
					$("#errorInstrument").text("Instrument Id is empty!");
					  return;
				}
                idWithMarket = idWithMarket.split(",");
                var instrumentId = idWithMarket[0];
                var market = idWithMarket.length > 1 ? idWithMarket[1] : null;
				if(instrumentId.length>50){
					$("#errorInstrument").text("Instrument Id is too long (maximum 50 characters)!");
					  return;
				}
				var RowIds = getSelectedRowIds().toArray();
				var rowdata = $jqGrid.jqGrid("getRowData", RowIds[0]);
				GetBookAssetHelper.doCheckInstrumentId(instrumentId, market,rowdata.agreementId, rowdata.movementRequired, rowdata.workflowId,
		    			directToBookPage);
    		 
    		}
				
		    function directToBookPage(str){
			  	if("false" == str) {
					   $("#errorInstrument").text("This instrument is not eligible. It is outside of the parameters selected for eligibility.");
			        	return;
			        }
			  	if(str.length == 0){
			        	//$("#errorInstrument").text("This security does not exist or is not unique or not include by this agreement. Please make sure it is correctly spelt and exists within the system.");
			        	$("#errorInstrument").text("This security does not exist or is not unique. Please make sure it is correctly spelt and exists within the system.");
			            return;
			         }
			  	var errorStr = 'error'; 
			    if(str.indexOf(errorStr) >= 0) {
			            var msg = str.substring(str.indexOf(errorStr)+errorStr.length);
			            $("#errorInstrument").text('Illegal booking for asset:'+$("#instrumentId").val() + msg);
			            return ;
			        }
			    var ids = str.split('&');
			    if(ids.length != 8){
			        	$("#errorInstrument").text("This security does not exist or is not unique. Please make sure it is correctly spelt and exists within the system.");
			            return;
			         }
			     var changedArr = $jqGrid.jqGrid('getChangedCells','dirty');
			     var rows = checkForComment(changedArr);
					if(rows.length>0){
			        	$("#errorInstrument").text("Comments must be populated");
			         	return;
			        }
			    var RowIds = getSelectedRowIds().toArray();
			    var rowdata = getRowData(RowIds[0]);
			    var aaId = ids[0];
			    var cat = ids[1];
			    var securityId = ids[2];
			    var workflowId = ids[3];
			    var isForInst;
			        if(cat == 32){
			        	isForInst = "1";      	
			        }else if (cat == 33){
			        	isForInst = "2";
			        }else{ 
			        	isForInst = "3";
			        }
					sendSyncRequest({	
						method: 'saveDataBeforeAction',
						changedArr:JSON.stringify(changedArr),
						eventIds: getChangedUmbrellaIds(changedArr).join(",")
					});
					redirectWithTabId("/firmament/collateral/diaryManager/saveDiaryManager.do?aaIdOfInst="+aaId+"&catOfInst="+cat+"&securityIdOfInst="+securityId+"&workflowIdFromEE="+workflowId+"&isForInst="+isForInst+"&actionStrOfInst="+rowdata.movementRequired+"&isNew=New");
			}

			$("#instrumentId").autocomplete({
				source: function( request, response ) {
					var RowIds = getSelectedRowIds().toArray();
					var rowdata = getRowData(RowIds[0]);
					sendSyncRequest( {method: 'getInstrumentIds',agrId:rowdata.agreementId,maxSize:20,term: request.term }, response );
					}
				});	
			
			var editCategoryDialogFun = function() {
				//ajax save Data
				var bValid = $("#categoryItemform").validate().form();
				if(!bValid) return;

				var category = new Object();
				category.id = $selectedCategory.attr("id");
				category.label = $("#categoryLabel").val();
				category.desc = $("#categoryDesc").val();
				
				if (bValid) {
					
					sendSyncRequest({
							method: 'updateCatagory',
							cfgId: cfgId,
							category: JSON.stringify(category)
						}, function(result) {
							cfgId = result;
						}
					);
												
					$(this).dialog('close');
	
					$selectedCategory.attr("title", category.desc);
					$selectedCategory.find("a").text(category.label);
					
				}
				
			}
			
			var delCategoryDialogFun = function() {
				sendSyncRequest({	
					method: 'delCatagory',
					cfgId: cfgId,
					categoryId: $selectedCategory.attr("id")
				}, function(data){
                   cfgId = data;
                });
							
				$selectedCategory.remove();
				
				$(this).dialog('close');
			}
			
			var addItemDialogFun = function(){
				var bValid = $("#filterItemform").validate().form();
				if(!bValid) return;
				
				var filterName;
                var columnSetting = 'default';
				var $copyItem;
				if($("#copyfilter").val()!=""){
					filterName = $("#copyfilter").val();
					columnSetting = $("#" + filterName).parent().attr("columnSetting");
				}
                
				var accordionItem = new Object();
				accordionItem.label = $("#itemLabel").val();
				accordionItem.desc = $("#itemDesc").val();
				accordionItem.icon = $sysIcons.find(".ui-selected").attr("title")||'iCall';

				if(!filterName){
					$copyItem = $(".sysFilterItems li:first", "#accordions").clone()
									.find("input[name='tabPage']").remove().end()
									.attr("columnSetting", "default").find("b").text("").end();
				}else{
					$copyItem = $("li[filter="+filterName+"]", "#accordions").clone();
				}
				
				$(this).dialog('close');
				$copyItem.appendTo($selectedCategory.next().children("ul")).attr("class", accordionItem.icon)
					.attr("title", accordionItem.desc).find("font").text(accordionItem.label);
				sendSyncRequest({
					method: 'createItem',
					cfgId: cfgId,
					filterName: filterName,
                    columnSetting:columnSetting,
					categoryId: $selectedCategory.attr("id"),
					item: JSON.stringify(accordionItem)
				},  function(result){
					cfgId = result.id;
					itemId = result.itemId;
					$copyItem.attr("id", result.itemId).attr("filter", result.dataFilterId).attr("columnSetting", result.columnSettingId);
					$copyItem.find(":hidden:first").attr("id", result.dataFilterId);
					$copyItem.find("b").attr("itemid", result.itemId);
				});

				if(filterName){
					var $orgInputs = $("li[filter="+filterName+"]", "#accordions").find("input:hidden");
					var $newInputs = $copyItem.find("input:hidden");
					var newName ="";
					$orgInputs.each(function(i){
						var that = this;
						$newInputs.each(function(j){
							if(j>0 && that.name!=""){
								if(newName!=that.name){
									newName = that.name;
									$(this).attr("name",that.name);
									$(this).val(that.value);
								}
							}
						});
					});
				}
				
				$copyItem.addClass("item-click").siblings().removeClass("item-click");
				bindFilterItemEvent($copyItem);
				
				$copyItem.trigger('click');
				addOption(getfilterIdByItem(itemId),accordionItem.label);
			}
			
			var editItemDialogFun = function() {
				//ajax save Data
				var bValid = true;

				var accordionItem = new Object();
				accordionItem.id = $selectedItem.attr("id");
				accordionItem.label = $("#itemLabel").val();
				accordionItem.desc = $("#itemDesc").val();
				accordionItem.icon = $sysIcons.find(".ui-selected").attr("title");

				if (bValid) {
					
					sendSyncRequest({
							method: 'updateItem',
							cfgId: cfgId,
							item: JSON.stringify(accordionItem)
						}, function(result) {
							cfgId = result;
						}
					);
												
					$(this).dialog('close');
	
					$selectedItem.attr("class", accordionItem.icon);
					$selectedItem.attr("title", accordionItem.desc);
					$selectedItem.find("font").text(accordionItem.label);
					
				}
			}
			
			var delItemDialogFun = function() {
				sendSyncRequest({	
					method: 'delItem',
					cfgId: cfgId,
					categoryId: $selectedItem.parent().parent().prev().attr("id"),
					itemId: $selectedItem.attr("id")
				}, function(data){
                   cfgId = data;
                });
				removeOption($selectedItem.attr("filter"));		
				$selectedItem.remove();
				
				$(this).dialog('close');
			}
			
			// ** add item edit & del dialog
			var $dialogConfirm = $("#dialog-confirm").dialog({
				autoOpen: false,
				resizable: false,
				height:140,
				modal: true
//				buttons: {
//					'Delete': delItemDialogFun,
//					Cancel: cancelDialogFun
//				}
			});
			
			var dialogCallback;
			function showConfirmMsg(msg, callback) {
			    dialogCallback = callback;
			    
				$('#confirmMessageBody').html(msg);
                $dialogMovementDirection.dialog('open');
            };
			
			var $dialogConfirmMsg = $("#dialog-confirmMsg").dialog({
				autoOpen: false,
				resizable: false,
				height:140,
				modal: true,
				buttons: {
					'OK': function() {
						$(this).dialog('close');
						dialogCallback(true);
					},
					Cancel: cancelDialogFun
				}
			});
			
   			var $dialogtransfer = $("#dialog-transfer").dialog({
				autoOpen: false,
				position: [0,78],
				height: $("#mainContent").height(),
				width: $(this).width(),
				modal: true
			});
			
			var $dialogbook = $("#dialog-book").dialog({
				autoOpen: false,
				position: [0,78],
				height: $("#mainContent").height(),//$(window).height()
				width: $(this).width(),
				modal: true
			});
			
			var $dialogcategory = $("#dialog-category").dialog({
				autoOpen: false,
				height: 250,
				width: 400,
				show: 'scale',
				hide: 'explode',
				modal: true
//				buttons: {
//					'Save': editDialogItemFun,
//					Cancel: cancelDialogFun
//				},
			});
		
			var $dialogitem = $("#dialog-item").dialog({
				autoOpen: false,
				height: 250,
				width: 400,
				show: 'scale',
				hide: 'explode',
				modal: true
//				buttons: {
//					'Save': editDialogItemFun,
//					Cancel: cancelDialogFun
//				},
			});	
			var $dialogInstrumentId = $("#dialog-instrumentId").dialog({
				autoOpen: false,
				height: 250,
				width: 350,
				show: 'scale',
				hide: 'explode',
				modal: true
//				buttons: {
//					'Save': editDialogItemFun,
//					Cancel: cancelDialogFun
//				},
			});	
			
			window.closeBulkBooking = function () {
				$dialogbook.dialog('close');
				triggerToolbarSearch();
				
			}
	
			window.closeTransferBooking = function () {
				$dialogtransfer.dialog('close');
				//var params = getMergedParamObj();
				//$jqGrid.jqGrid("appendPostData", params);
				triggerToolbarSearch();
			}
			
			//check whether from other page
			 <c:if test="${!empty dynamicFilterItems}">
			 	$("#dynamic", "#accordions").trigger('click');
			 </c:if>
			 
		});
		
		//Last step of init this page get counts for default filters
		setAmountsForFilters = function(data){
			jQuery.each(data, function (key, value) {
				jQuery("#" + key).siblings("b").html("("+value+")");
			});
		}

		setResultData = function(data){
			if(data.isNeedCalcStatement){
				if(data.webguiEeDistRegMsg)
					log(data.webguiEeDistRegMsg, false);
				if(data.webguiEEDistMsg)
					log(data.webguiEEDistMsg, false);
			}
			setAmountsForFilters(data.amountsMap);
		}

		function updateCountsForDefaultFilters(needCalcStatement){
			sendSyncRequest({	
				//check whether from other page
				<c:if test="${!empty dynamicFilterItems}">
					<c:forEach items="${dynamicFilterItems}" var="filterItem">
						${filterItem.fieldName}:'${filterItem.filterValue}',
					</c:forEach>
				</c:if>
				isNeedCalcStatement: needCalcStatement,
				method: 'getCountForDefaultFilters'
			}, setResultData);
		}
		// get filter counts by AJAX
		jQuery(function($) {
			updateCountsForDefaultFilters("true");
		});
			
		//get counts for each filters when user click filter category only at the first time.
		function updateCountsForUserFilters(categoryId){
			sendSyncRequest({	
				method: 'getCountForUserFilters',
				categoryId: categoryId
			}, setAmountsForFilters);
		}
	
		jQuery(function($) {
			$("#accordions h3").click(function(){
				categoryId = this.id;
				updateCountsByCategoryId(categoryId);
			});
		});

		function updateCountsByCategoryId(categoryId){
			if(categoryId != "default"){	
				updateCountsForUserFilters(categoryId);
			}else{
				updateCountsForDefaultFilters("false");
			}
		}

		function blockUI() {
			jQuery(".ui-layout-west").block({ message: null,overlayCSS:{backgroundColor: '#000', opacity: 0.3 }}); 
			jQuery("#mainContent").block({ 
				message: null, //'<h1><img src="common/newEEImage/loading.gif" alt="loading.." /> Loading...</h1>', 
//				css: { 
//		            border: 'none', 
//		            padding: '15px', 
//		            backgroundColor: '#000', 
//		            '-webkit-border-radius': '10px', 
//		            '-moz-border-radius': '10px', 
//		            opacity: 0.5, 
//		            color: '#fff' 
//	        	},
				overlayCSS:  { 
			        backgroundColor: '#000', 
			        opacity: 0.3 
			    }
			}); 
		}
		
		// ** jQuery form validation
		jQuery(function($) {
			// validate filter item form on keyup
			$("#filterItemform").validate({
				rules: {
					itemLabel: "required"
				},
				messages: {
					itemLabel: "Enter your item Name"
				},
				// the errorPlacement has to take the table layout into account
				errorPlacement: function(error, element) {
					error.appendTo( element.parent().next() );
				},
				// specifying a submitHandler prevents the default submit, good for the demo
				submitHandler: function() {
					alert("submitted!");
				},
				// set this class to error-labels to indicate valid fields
				success: function(label) {
					// set &nbsp; as text for IE
					label.html("&nbsp;").addClass("checked");
				}
			});
			// validate category item form on keyup
			$("#categoryItemform").validate({
				rules: {
					categoryLabel: "required"
				},
				messages: {
					categoryLabel: "Enter your Category Name"
				},
				// the errorPlacement has to take the table layout into account
				errorPlacement: function(error, element) {
					error.appendTo( element.parent().next() );
				},
				// specifying a submitHandler prevents the default submit, good for the demo
				submitHandler: function() {
					alert("submitted!");
				},
				// set this class to error-labels to indicate valid fields
				success: function(label) {
					// set &nbsp; as text for IE
					label.html("&nbsp;").addClass("checked");
				}
			});
			
		});
		
		autoComplete = function(elem) {
						
			jQuery(elem).autocomplete(
				{
					minLength : 0,
					source : function(request, response) {

						var availableTags;
						var eleId = this.element.attr("id");
						if(eleId == "gs_movementRequired") {
							//alert("Movement")
							availableTags = [ "Call", "Recall", "Delivery", "Return", "ITM No Calls","OTM No Calls" ];
						} else if(eleId == "gs_autoBookingApplicability"){
							//alert("Applicability")
							availableTags = [ "IM", "TSA", "VM"];
						}
					
						// delegate back to autocomplete, but extract the last term
						response(jQuery.ui.autocomplete.filter(availableTags,
								extractLast(request.term)));
					},
					focus : function(e, i) {
						return false;
					},
					select : function(event, ui) {
						if(jQuery.inArray(ui.item.value, split(this.value.trim())) !== -1) {
							return false;
						}
						var terms = split(this.value);
						// remove the current input
						terms.pop();
						// add the selected item
						terms.push(ui.item.value);
						// add placeholder to get the comma-and-space at the end
						terms.push("");
						this.value = terms.join(", ");
						return false;
					}
				}).focus(function(){            
					jQuery(this).trigger('keydown.autocomplete');
		        });
		}
		
		autoCompleteRemote = function(elem) {
			// don't navigate away from the field on tab when selecting an item
			jQuery(elem).bind( "keydown", function( event ) {
				if ( event.keyCode === jQuery.ui.keyCode.TAB &&
						jQuery( this ).data( "autocomplete" ).menu.active ) {
					event.preventDefault();
				}
			})
			.autocomplete({
				source: function( request, response ) {
					var pricURL = parseUrlWithWinName('organisation/pricAutoCompleteSearch.do');
					var cptyURL = parseUrlWithWinName('organisation/cptyAutoCompleteSearch.do');
					var descURL = parseUrlWithWinName('collateral/flexibleEE/ajaxCall.do?method=searchByDesc');
					var ccpURL = parseUrlWithWinName('collateral/flexibleEE/ajaxCall.do?method=searchByCCP');
					var linkageSetURL = parseUrlWithWinName('collateral/flexibleEE/ajaxCall.do?method=searchByLinkageSet');
					var statementSetURL = parseUrlWithWinName('collateral/flexibleEE/ajaxCall.do?method=searchByStatementSet');
					
					//var groupURL = parseUrlWithWinName('collateral/flexibleEE/ajaxCall.do?method=searchByGroup');
					var groupURL= parseUrlWithWinName('collateral/groupAutoCompleteSearch.do');
					
					var regionURL=parseUrlWithWinName('collateral/regionAutoCompleteSearch.do');
					var url = pricURL;
					var searchType=1;
					var searchName = this.element.attr("id");
					
					if(searchName == 'gs_principalCode') {
						searchType = 2;
					} else if (searchName == 'gs_principalName') {
						searchType = 0;
					} else if (searchName == 'gs_principalLongName') {
						searchType = 1;
					} else if (searchName == 'gs_custodian') {
						url = cptyURL;
						searchType = 1;
					}else if(searchName=='gs_group'){
						url = groupURL;
						searchType = 2;
					}else if(searchName=='gs_region'){
						url = regionURL;
						
					}else if (searchName == 'gs_counterpartyCode') {
						url = cptyURL;
						searchType = 2;
					} else if (searchName == 'gs_counterpartyName') {
						url = cptyURL;
						searchType = 0;
					} else if (searchName == 'gs_counterpartyLongName') {
						url = cptyURL;
						searchType = 1;
					} else if( searchName == 'gs_description') {
						url = descURL;
					} else if( searchName == 'gs_ccp') {
						url = ccpURL;
					} else if( searchName == 'gs_group') {
						url = groupURL;
					} else if( searchName == 'gs_linkageSet') {
						url = linkageSetURL;
					} else if( searchName == 'gs_statementSet') {
						url = statementSetURL;
					} 
					
					
					sendSyncRequest( {term: extractLast( request.term ), searchType: searchType}, 
						response, 'json', url );
				},
				search: function() {
					// custom minLength
					var term = extractLast( this.value );
					if ( term.length < 2 ) {
						return false;
					}
				},
				focus: function(e, i) {
					// prevent value inserted on focus
					return false;
				},
				select: function( event, ui ) {
					var terms = split( this.value );
					// remove the current input
					terms.pop();
					jQuery.each(terms, function(index, value) {
						terms[index] = value.trim();
					});
					
					if(ui.item.value.indexOf(",") != -1) ui.item.value = "'" + ui.item.value + "'";
					
					if(jQuery.inArray(ui.item.value, terms) === -1) {
						// add the selected item
						terms.push( ui.item.value );
					} 

					// add placeholder to get the comma-and-space at the end
					terms.push("");
					this.value = terms.join( ", " );
					
					return false;
				}
			});
		}

		function calcMsgPanelHeight() {
			var calcValue = jQuery("#mainContent").height() 
									- jQuery("#p3 .item-header").outerHeight(true)
									- jQuery("#p4").outerHeight(true) 
									- jQuery("#p5").outerHeight(true);
			return calcValue;
		}
		
		function calcGridHeight() {
           	var calcValue = jQuery("#mainContent").height() 
		           				- jQuery("#p3").outerHeight(true) 
		           				- jQuery("#p5").outerHeight(true) 
		           				- jQuery("#p4 .item-header").outerHeight(true) - 72;
           	
           	return calcValue > 0 ? calcValue : 0;
        }
		
		function executeFunctionByName(functionName, context /*, args */) {
		    var args = Array.prototype.slice.call(arguments).splice(2);
		    var namespaces = functionName.split(".");
		    var func = namespaces.pop();
		    for(var i = 0; i < namespaces.length; i++) {
		    	context = context[namespaces[i]];
		    }
		    return context[func].apply(this, args);
		}
		//executeFunctionByName("My.Namespace.functionName", window, arguments);

		function split(val) {
			return val.split(/,(?=(?:[^']|'[^']*')*$)/g);
		}
		
		function extractLast(term) {
			return split(term).pop().trim();
		}
		
		function log(message, success) {
			if(!success) {
				var logHeader = "normalMessage";
				if(message.indexOf("calcMsg:") != -1){
					logHeader = "calcMessage";
					jQuery("#log div[name='" + logHeader + "']").remove();
					
					message = message.substring(message.indexOf("calcMsg:")+"calcMsg:".length);
				}
				if(message != "null"){
                    var date = getCurrentDate();
                    var dateString="["+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+"]";
					jQuery( "<b><div name="+logHeader+"/></b>" ).html(dateString +"&nbsp;&nbsp;" + message + "<br>").addClass("failureLog").prependTo("#log");
				}
			} else {
				if(message["invokeMethod"]) {
//					(new Function("return " + message["invokeMethod"] + "(emailItem)"))(message.data);
					window[message["invokeMethod"]](message.data);
				}
				
				// don't show the log message in this period
				//jQuery( "<div/>" ).text(getCurrentTime() + " :    " + message).addClass("successLog").prependTo("#log");
			}
			jQuery( "#log" ).attr( "scrollTop", 0 );
		}

		function showEmailMsg(emailItem) {
			var $emailMsg = jQuery("#emailMsg").clone().removeAttr("id");
			var $emailTable = $emailMsg.find("table");
			var $templateRow = $emailTable.find("tr").last();

			if(emailItem["total"]) {
				$emailMsg.find("span em").first().text(emailItem["success"]).end().last().text(emailItem["total"] - emailItem["success"]);
			} else {
				$emailMsg.find("span").first().remove();
			}
             //add red time tag in front of the "Batch processed: Successfully Delivered"
            var date=getCurrentDate();
            var dateString="["+date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()+"]";
            jQuery("#timeTag",$emailMsg).css("color", "#FF0000").text(dateString);
			var results = emailItem.eventLogs;
			for(var i=0; i<results.length; i++) {
				var $copyRow = $templateRow.clone();
				var $copyCells = $copyRow.children();
				
				$copyCells.first().text(results[i].timeStamp);
				if(results[i].level == 'info') {
//					$copyCells.eq(1).find("font").css("color", "#000000");
				} else if(results[i].level == 'warn') {
					$copyCells.eq(1).find("font").css("color", "#FFCC00");
				} else if(results[i].level == 'error') {
					$copyCells.eq(1).find("font").css("color", "#FF0000");
				}
				$copyCells.eq(1).find("b").text(results[i].level);
				$copyCells.eq(2).text(results[i].source);
				$copyCells.last().text(results[i].msg);
				
				$copyRow.appendTo($emailTable);
				$copyRow.show();
			}
			$templateRow.remove();
			$emailTable.find("tBody tr:even").addClass("odd");
			$emailMsg.prependTo("#log");
			$emailMsg.show();
			
			jQuery(".ui-layout-west, #mainContent").unblock();
		}
		

		function sendAjaxRequest(data, callback) {
			jQuery.get(parseUrlWithWinName("collateral/flexibleEE/ajaxCall.do"), data, function(result) {
				if(!errorsCheck(result)){
					callback(result.data);
				}
			});
		}
		
		function sendSyncRequest(data, callback, dtype, url, sync) {
			if(!dtype) dtype = 'json';
			if(!url) url = parseUrlWithWinName('collateral/flexibleEE/ajaxCall.do'); 
			var async = true;
			if(sync) async = false;
			jQuery.ajax({
	            url : url,
	            type : 'GET',
	            dataType : dtype,
	            data : data,
				async: async,
	            success: function(result) {
	            	if(!sessionTimeOutCheck(result)){
						if(!result) return;
		        		if(result.message)  {
		        			log(result.message, result.success);
		        		}
		        		
		        		if(result.success) {
		        			callback(result.data);
		        		} else {
							jQuery(".ui-layout-west, #mainContent").unblock();
						}
		        	}
		        },
				error: function(XMLHttpRequest, textStatus, errorThrown){
					if (!sessionTimeOutCheck(errorThrown)) {
		        		log("An error has happened in AJAX request.");
		        	}
				}
    		});
		}
		
		function sessionTimeOutCheck(result) {			
	        var reg = /<html>/ig;  
		    var isExpired = reg.test(result);
		    if(isExpired) { 
			    sessionTimeOutAction();
		    }
		    
	        return isExpired;
		}

		function sessionTimeOutAction() {
      		window.alert("Your session has expired, please login again.");
      		redirectWithTabId("/firmament/index.do");
		}

		jQuery(function() {
			Layout.init("HistoryBar");
		});

	</script>
  </head>
  <lrmhtml:beansetup name="diaryManagerSearchForm" bean="diaryManagerSearchForm" lookupBean="lookup" />
<body>
	<div id="loading">Loading content, please wait..  <img src="common/newEEImage/loading.gif" alt="loading.." /></div>
	
	<div id="dialog-transfer" title="Transfer Page">
   	</div>
	
   	<div id="dialog-book" title="Bulk Book">
   	</div>

	 <div id="dialog-comments" title="Save to">
		<textarea cols="65" rows="12" id="txtComments" maxLength="4000"  style= "overflow-y:auto;" class="ui-widget-content">
		</textarea>
		
	</div>
	 <div id="dialog-instrumentId" title="Instrument Id">
	 	<br/>
	 	<br/>
	 	<label>Instrument Id:</label>
		<input type="text" id="instrumentId" style="overflow-y:auto;" class="ui-widget-content"/>
		<br/>
		<br/>
		<span id="errorInstrument"></span>
		
	</div>
	<div id="dialog-ccyExchange" title="CurrencyExchange">
		<html:form action="/collateral/flexibleEE/viewPage">
	<table border="0" cellspacing="0" cellpadding="8" class="pagetext">
		<tr>
			<td nowrap="true" class="label"><b>Original Currency</b></td>
			<td class="field">
			<html:select styleId="originalCurrency"  property="originalCurrency" >
        	<html:optionsCollection name="lookup" property="lookup(currency)" label="value" value="id"/> 
      		</html:select>

			</td>			
		</tr>
		<tr>
			<td nowrap="true" class="label"><b>Original Amount</b></td>
			<td class="field">
				<textarea id="_originalAmount" cols="20" rows="1" style="overflow-y:auto;" class="ui-widget-content">
				</textarea>
			</td>			
		</tr>
		<tr>
			<td nowrap="true" class="label"><b>Result Currency</b></td>
			<td class="field">
			<html:select styleId="resultCurrency"  property="resultCurrency" >
        	<html:optionsCollection name="lookup" property="lookup(currency)" label="value" value="id" /> 
      	</html:select>
      </td>
      </tr>	
      <tr>
      	<td colspan=2>
     		<span id="errorMsg"></span>
		</td>
	  </tr>	
	</table>
	</html:form>
			
	</div>
	 
	<div id="dialog-category" title="Category Edit">
		<form id="categoryItemform" class="validationform" autocomplete="off" method="get" action="">
	  		<table>
	  		  <tr>
	  		  	<td class="label"><label id="lcategoryLabel" for="categoryLabel">Name</label></td>
	  		  	<td class="field"><input id="categoryLabel" name="categoryLabel" type="text" value="" maxlength="100" /></td>
	  		  	<td class="status"></td>
	  		  </tr>
	  		  <tr>
	  			<td class="label"><label id="lcategoryDesc" for="categoryDesc">Description</label></td>
	  			<td class="field"><input id="categoryDesc" name="categoryDesc" type="text" value="" maxlength="100" /></td>
	  		  </tr>
	  		</table>
          </form>
	</div>
	
	<div id="dialog-item" title="Item Edit">
		<form id="filterItemform" class="validationform" autocomplete="off" method="get" action="">
	  		<table>
	  		  <tr>
	  		  	<td class="label"><label id="litemLabel" for="itemLabel">Name</label></td>
	  		  	<td class="field"><input id="itemLabel" name="itemLabel" type="text" value="" maxlength="100" /></td>
	  		  	<td class="status"></td>
	  		  </tr>
	  		  <tr>
	  			<td class="label"><label id="litemDesc" for="itemDesc">Description</label></td>
	  			<td class="field"><input id="itemDesc" name="itemDesc" type="text" value="" maxlength="100" /></td>
	  			<td class="status"></td>
	  		  </tr>
	  		  <tr>
	  			<td class="label"><label id="litemIcon">Icon</label></td>
	  			<td class="field">
					<ul id="sysIcons">
						<li class="iCall" title="iCall"><span class="item_bg_position"></span></li>
						<li class="iReCall" title="iReCall"><span class="item_bg_position"></span></li>
						<li class="iDelivery" title="iDelivery"><span class="item_bg_position"></span></li>
						<li class="iReturn" title="iReturn"><span class="item_bg_position"></span></li>
						<li class="iIssued" title="iIssued"><span class="item_bg_position"></span></li>
					</ul>
	  			</td>
	  		  </tr>
	  		  <tr>
	  			<td class="label"><label id="copyFilterLable">Copy Filter</label></td>
	  			<td class="field">
	  				<select id="copyfilter">
						<option value =""></option>
						<c:forEach items="${wrapper.categories}" var="category">
							<c:forEach items="${category.items.item}" var="item">
							<option value ="${item.dataFilterRef}">${item.label}</option>
							</c:forEach>
						</c:forEach>
					</select>
	  			</td>
	  		  </tr>
	  		</table>
          </form>
	</div>
	
	<div id="dialog-confirm" title="Confirm">
		<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
			The item will be permanently deleted and cannot be recovered. Are you sure?</p>
	</div>
	
	<div id="dialog-confirmMsg" title="Confirm">
		<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>
			<div id="confirmMessageBody"></div>
		</p>
	</div>

	<div class="ui-layout-west" style="overflow:hidden;">
        <div class="header ui-widget-header">
        	Navigation
        	<span id="saveOrderBtn" class="ui-icon ui-icon-disk" title="Save Item Order"></span>
        </div>
        <div class="content">
        	<div id="accordions">
				<c:forEach items="${wrapper.categories}" var="category">
					<h3 id="${category.id }" title="${category.desc}">
						<a href="#">${category.label }</a>
						<span class="ui-icon ui-icon-plusthick" style="left:9em"></span>
						<span class="ui-icon ui-icon-pencil" style="left:10em"></span>
<!--						<span class="ui-icon ui-icon-closethick" style="left:11em"></span>-->
					</h3>
					<div style="padding: 0; border:none">
	                    <ul class='<c:choose><c:when test="${category.id ne 'default'}">connectedSortable</c:when><c:otherwise>sysFilterItems</c:otherwise></c:choose> ui-helper-reset'>
						
							<c:forEach items="${category.items.item}" var="item">
								<c:set var="filterName" value="${item.dataFilterRef}" />
								<li id="${item.id }" class="${item.icon }" title="${item.desc}" filter="${filterName}" columnSetting="${item.columnSettingRef}">
									<input type="hidden" id="${filterName}" />
									<c:choose>
										<c:when test="${filterName eq 'dynamicFilter'}">
											<c:forEach items="${dynamicFilterItems}" var="filterItem">
												<input type="hidden" id="${filterItem.fieldName}"  name="${filterItem.fieldName}" value="${filterItem.filterValue}" />
											</c:forEach>
											 <c:if test="${!empty dynamicFilterItems}">
											 	<input type="hidden" id="multiOrder"  name="multiOrder" value="1" />
											 </c:if>
										</c:when>
										<c:otherwise>
											<c:forEach items="${(wrapper.dataFilterMap[filterName]).dataFilterItem}" var="filterItem">
												<input type="hidden" id="${filterItem.fieldName}"  name="${filterItem.fieldName}" value="${filterItem.filterValue}" />
											</c:forEach>
										</c:otherwise>
									</c:choose>
									<span class="item_bg_position"></span>
									<font style="FONT-SIZE: 10px; *FONT-SIZE: 10px;">${item.label }</font>
									<b itemId="${item.id }"></b>
									<a href="javascript:void(0)" class="icon-size cross"></a>	
									<a href="javascript:void(0)" class="icon-size pencil"></a>	
								</li>
							</c:forEach>
						</ul>
					</div>
				</c:forEach>
				
			</div>
        </div>
	        	
	</div>
	
<%--	<div  class="ui-layout-east">-->--%>
<%--        <div class="header ui-widget-header">Actions</div>--%>
<%--	    <div class="contents">--%>
<%--			<ul style="list-style-type: none" id="actions">--%>
<%--			<c:forEach items="${wrapper.actionBtns}" var="actionBtn">--%>
<%--				<li class="${actionBtn.icon}" title="${actionBtn.desc}" baseURL="${actionBtn.baseURL}" param="${actionBtn.params}" --%>
<%--				style="cursor: pointer; display: none; margin-left: 20px; margin-top: 5px; margin-bottom: 5px; ">--%>
<%--					<span class="action_bg_position"></span>--%>
<%--				</li>--%>
<%--			</c:forEach>--%>
<%--		</ul>--%>
<%--        </div>--%>
<%--	</div>--%>

	<div class="ui-layout-north" style="overflow: hidden;">
        <div class="top-header">
        	<table border="0" width="100%" cellspacing="0" cellpaddiing="0" cellpadding="0" height="100%">
			  <tr class="middle"> 
			    <td class="noprint" height="24" valign="top">
			    	<%@ include file="/appwindow/top.jsp" %>
			    </td>
			  </tr>
			  <tr id="eMenuBar"> 
			    <td class="noprint" height="20" valign="top"><tiles:insert page="/getMenu.do" flush="false"/><%@ include file="/appwindow/applicationList.jsp"%></td>
			  </tr>

				<tr>
					<td height="1" class="actionshadow"></td>
				</tr>
				<tr>
					<td height="2" class="actionmiddle"></td>
				</tr>
				<tr>
					<td height="6" class="actiondivider"></td>
				</tr>
				<tr>
					<td height="1" class="actionshadow"></td>
				</tr>
				<tr>
					<td height="1" class="actionmiddle"></td>
				</tr>
				<tr>
					<td height="20" class="actionshadow" valign="top"><%@ include file="/common/history.jsp" %></td>
				</tr>
				<tr>
					<td height="1" class="actionmiddle"></td>
				</tr>
				<tr>
					<td height="1" class="actionshadow"></td>
				</tr>
				<tr>
					<td height="1" class="actiondarkshadow"></td>
				</tr>

			</table>
		</div>
	</div>

	<div class="ui-layout-south">
        <div class="em-bottom">
        	<%@ include file="/appwindow/bottom.jsp" %>
        </div>
	</div>

	<div id="mainContent" style="overflow: hidden;">
		<div class="main-item" id="p1" style="display: none;">
			<div class="item-header">Trigger Alert</div>
			<div class="item-content">
				<div>Trigger Alert</div>	
				<div>Trigger Alert...</div>	
			</div>
		</div>
		
		<div class="main-item" id="p2" style="display: none;">
			<div class="item-header">CCP Daily Summary Screen</div>
			<div class="item-content">
				<span>CCP Group1</span>
				<div class="ccp_group ui-widget-content"></div>
			</div>
		</div>
		<div class="main-item" id="p3">
			<div class="item-header">Message</div>
            <div class="item-content" style="height: 48px; overflow-y: auto">
                <div id="log">
                    <div id="emailMsg" align="left" style="display:none;">
						<span class="pagetext">
							<b><span id="timeTag"></span></b>
							<b>Batch processed: Successfully Delivered: <em></em> Unsuccessful: <em></em></b>
						</span>
                        <table width="100%" border="0" cellspacing="0" cellpadding="8" style="padding-left:40px">
                            <tbody>
                            <tr>
                                <td class="pagetext" height="15" width="20%" align="left"></td>
                                <td class="pagetext" height="15" width="10%" align="left"><font color="#000000"><b></b></font>
                                </td>
                                <td class="pagetext" height="15" width="10%" align="left"></td>
                                <td class="pagetext" height="15" width="60%" align="left"></td>
                            </tr>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
		</div>
		<div class="main-item" id="p5">
			<div class="item-header">Actions</div>
			<div class="item-content" style="height: 30px">
				<ul style="list-style-type: none;float:left;padding:0" id="actions">
					<c:forEach items="${wrapper.actionBtns}" var="actionBtn">
					<li class="${actionBtn.icon}" title="${actionBtn.desc}" baseURL="${actionBtn.baseURL}" param="${actionBtn.params}" 
						style="cursor: pointer; display: none; margin-left: 20px;margin-bottom: 2px;float:left ">
						<span class="action_bg_position"></span>
					</li>
					</c:forEach>
				</ul>
        	</div>	
		</div>
		<div class="main-item" id="p4">
			<div class="item-header">Exposure Management</div>
			<div class="item-content">
	       		<table id="jqGrid">
	        	</table>
				<div id="gridPager"></div>
			</div>
		</div>
	</div>
</body>
<script language="javascript">
	col_set_link_winname();
</script>
</html>
